你能帮我重构我为 Ruby Koans #182 提出的解决方案吗?这是您在其中编写得分方法来计算贪婪游戏分数的公案。以下代码有效,所有测试均通过。
但是,它感觉又长又不像 ruby 。我怎样才能让它变得更好?
def score(dice)
rollGreedRoll = Hash.new
rollRollCount = Hash.new
(1..6).each do |roll|
rollGreedRoll[roll] = roll == 1 ? GreedRoll.new(1000, 100) :
GreedRoll.new( 100 * roll, roll == 5 ? 50 : 0)
rollRollCount[roll] = dice.count { |a| a == roll }
end
score =0
rollRollCount.each_pair do |roll, rollCount|
gr = rollGreedRoll[roll]
if rollCount < 3
score += rollCount * gr.individualPoints
else
score += gr.triplePoints + ((rollCount - 3) * gr.individualPoints)
end
end
return score
end
class GreedRoll
attr_accessor :triplePoints
attr_accessor :individualPoints
def initialize(triplePoints, individualPoints)
@triplePoints = triplePoints
@individualPoints = individualPoints
end
end
最佳答案
我在 https://gist.github.com/1091265 上发布了重构演练。 .最终解决方案如下所示:
def score(dice)
(1..6).collect do |roll|
roll_count = dice.count(roll)
case roll
when 1 : 1000 * (roll_count / 3) + 100 * (roll_count % 3)
when 5 : 500 * (roll_count / 3) + 50 * (roll_count % 3)
else 100 * roll * (roll_count / 3)
end
end.reduce(0) {|sum, n| sum + n}
end
注意:
.reduce
是 .inject
关于Ruby Koans 182.重构帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6738715/