你能帮我重构一下我为Ruby Koans#182提出的解决方案吗?这是你在其中写一个分数方法来计算贪婪游戏的分数的公案.以下代码工作,所有测试都通过.
然而,感觉很长,没有红宝石般的感觉.我怎样才能让它变得更好?
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 …Run Code Online (Sandbox Code Playgroud) 我需要创建一个方法,它应该只接收1到6之间的数字数组作为参数.如果参数不同,我想用错误消息退出方法.
我想过使用双条件子句,例如:
if (dice.is_a? Array ) && ("elements of dice are numbers of range (1..6)")
do something
else print "error message"
Run Code Online (Sandbox Code Playgroud)
代替字符串"骰子的元素是范围的数字(1..6)"我尝试了以下代码,但不起作用:
dice.each { |num| num <= 6 }
Run Code Online (Sandbox Code Playgroud)
你会建议什么?
我正在做边缘小屋学习红宝石,而我却被贪婪的koan(182-183)卡住了一个神秘的错误.这里列出了规则
我知道我的代码是......令人印象深刻,我想我一旦我的逻辑声音(它可能不是)就重构它.
我感谢任何帮助.
def score(dice)
score = 0
if dice == []
return score
end
dice = dice.sort
dice = [1,1,4,5,6]
count = [0,0,0,0,0,0]
score = 0
dice.each do |face|
if face == 1
count[0]++
elsif face == 2 # this is line 45 with reported error
count[1]++
elsif face == 3
count[2]++
elsif face == 4
count[3]++
elsif face == 5
count[4]++
elsif face == 6
count[5]++
end
end
if count[0] >= 3
score+= 1000
count[0] = …Run Code Online (Sandbox Code Playgroud)