是否可以在类构造函数中使用参数? [英] Is it acceptable having parameter in class constructor?

查看:202
本文介绍了是否可以在类构造函数中使用参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个rubygem我写的,这是有用的计数字出现在一个文本,我选择把3个参数在类构造函数。



,但我想重构它的美好。
在你的经验中,更容易阅读/ mantain /使用作为API类的构造函数没有参数和很多setters / getters方法或像这样的代码,构造函数中的所有参数? / p>

TIA



Paolo

 code> def initialize(filename,words,hide_list)

if! filename.nil?
@filename = filename
@occurrences = read
else
@filename = STDIN
@occurrences = feed
end

@hide_list = hide_list
@sorted = Array(occurrences).sort {| one,two | - (one [1] = two [1])}
@words = words

end


解决方案

您可以使用rails方式,其中选项以散列形式提供:

  def initialize(filename = nil,options = {})
@hide_list = options [:hide_list]
@words = options [:words]

if filename
@filename = filename
@occurrences = read
else
@filename = STDIN
@occurrences = feed
end

@sorted = Array(occurrences).sort {| one,two | - (one [1] = two [1])}

end

然后你可以这样调用:

  WC.newfile.txt,:hide_list => ; %w(a到to),:words => %w(这里有些话)

或这:


$ b b

  wc = WC.new 
wc.hide_list =%w(a is)
wc.words =%w $ b


a rubygem I'm writing and that is useful for counting word occurrences in a text, I choose to put 3 parameters in class constructor.

The code is working, but I want to refactor it for niceness. In your experience, it's easier to read/mantain/use as API a class with a constructor with no params and a lot of setters/getters method or a code like this one, with all the params in the constructor?

TIA

Paolo

def initialize(filename, words, hide_list)

  if ! filename.nil?
    @filename = filename
    @occurrences = read
  else
    @filename = STDIN
    @occurrences = feed
  end

  @hide_list = hide_list
  @sorted = Array(occurrences).sort { |one, two| -(one[1] <=> two[1]) }
  @words = words

end

解决方案

You could do it the rails way, where options are given in a hash:

def initialize(filename = nil, options = {})
  @hide_list = options[:hide_list]
  @words = options[:words]

  if filename
    @filename = filename
    @occurrences = read
  else
    @filename = STDIN
    @occurrences = feed
  end

  @sorted = Array(occurrences).sort { |one, two| -(one[1] <=> two[1]) }

end

Then you can call it like this:

WC.new "file.txt", :hide_list => %w(a the to), :words => %w(some words here)

or this:

wc = WC.new
wc.hide_list = %w(a the is)
wc.words = %w(some words here)

这篇关于是否可以在类构造函数中使用参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆