我正在编写一个 rubygem,它对于计算文本中单词的出现次数很有用,我选择在类构造函数中放置 3 个参数。
代码可以工作,但我想重构它以使其美观。
根据您的经验,作为 API 读取/维护/使用一个带有没有参数的构造函数和大量 setter/getters 方法的类或像这样的代码(构造函数中包含所有参数)会更容易吗?
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
您可以通过 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.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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)