是否可以在类构造函数中使用参数?

Pao*_*ego 5 ruby refactoring constructor

我正在写一个rubygem,它对于计算文本中的单词出现很有用,我选择在类构造函数中放入3个参数.

代码正在运行,但我想重构它以获得好处.根据您的经验,使用没有参数和许多setter/getters方法或类似代码的构造函数来读取/保留/使用API​​作为API更容易,构造函数中包含所有参数?

TIA

保罗

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
Run Code Online (Sandbox Code Playgroud)

mck*_*eed 3

您可以通过 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
Run Code Online (Sandbox Code Playgroud)

然后你可以这样调用它:

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

或这个:

wc = WC.new
wc.hide_list = %w(a the is)
wc.words = %w(some words here)
Run Code Online (Sandbox Code Playgroud)