我正在尝试为模块函数创建私有辅助方法,但无济于事。我觉得我缺少一些非常简单的东西。
使用更易于理解的用例更新了示例:
module FancyScorer
module_function
def score(ary)
scores = []
ary.each_slice(2).with_index do |slice, i|
scores <<
case i % 2
when 0
score_eventh(ary)
else
score_oddth(ary)
end
end
scores.inject(:+)
end
private
def score_eventh(ary)
ary.inject(:+) / (ary.size - 1)
end
def score_oddth(ary)
ary.inject(:*) / (ary.size - 1)
end
end
FancyScorer.score([1,2,3,4])
# => `block in score_curiously': undefined method `score_eventh'
# for FancyScorer:Module (NoMethodError)
注意:私有方法应该保持私有。
这是用例:有几个模块包含各种评分技术,例如FancyScorer
、SimpleScorer
、ComplexScorer
。这些函数被独立测试,然后被用来score
为不同的类创建一个方法。例如:
class A
...
def score
FancyScorer.score(metrics) + 2*SimpleScorer.score(metrics)
end
end
class B
...
def score
0.5*FancyScorer.score(metrics) + 2*SimpleScorer.score(metrics[0,3]) + ComplexScorer.score(metrics)
end
end
没有提供用例的上一个示例:
module Party
module_function
def pooper
enjoy
end
private
def enjoy
puts "Wahoo!"
end
end
Party.pooper
# => NameError: undefined local variable or method `enjoy' for Party:module
# from (party): in `pooper`