我是 Ruby 的新手,一般来说都是编程。我正在研究Ruby Koans。在卡住之前,我已经达到了 176/274。
这是“计分项目”,我需要编写一个方法来计算给定掷骰子的分数。
这可能不是你见过的最优雅的代码,但这是我想出的:
def score(dice)
tally = 0
tally += (dice.sort.to_s[/[1]+/].length % 3) * 100
if dice.sort.to_s[/[1]+/].length >= 3
tally += 1000
end
tally = tally + (dice.sort.to_s[/[5]+/].length % 3) * 50
if dice.sort.to_s[/[5]+/].length >= 3
tally += 500
end
if dice.sort.to_s[/[2]+/].length >= 3
tally += 200
end
if dice.sort.to_s[/[3]+/].length >= 3
tally += 300
end
if dice.sort.to_s[/[4]+/].length >= 3
tally += 400
end
if dice.sort.to_s[/[6]+/].length >= 3
tally += 600
end
return tally
end
第一个测试是:score([])需要返回0
当我运行它时,我得到“nil:NilClass 的未定义方法 `length'”(引用的行是 .length 的第一个实例)这告诉我“dice.sort.to_s[/[1]+/]”与“ score([])" 是 nil,但是当我在 irb>> 中运行它时,它是 0。
是什么赋予了?