我是Ruby的新手。当我使用Ruby Koans,About_Scoring_Project时,我遇到了一些问题。 .map方法根据短语的顺序返回值,而不是变量的名称。我很困惑......
def score(dice)
total_score = 0
side = 6
count = Array.new
side.times{count << 0} # [0, 0, 0, 0, 0, 0]
# Tell the occured time of each side
while i = dice.pop
count[i-1] += 1
end
# Calculating total score
i = 0
count.map! do |item|
i += 1
if item >= 3 && i != 1
total_score = i*100
item - 3
elsif item >= 3
total_score = 1000
item - 3
else
item
end
end
# Count the rest
total_score += ( count[0]*100 + count[4]*50 )
total_score # return the total score
end
虽然这个有用,但是当我最初写的时候:
elsif item >= 3
item - 3
total_score = 1000
执行
时,数组计数结果为[1000,0,0,0,0,0] score([1,1,1]) # score([1,1,1]) = 101000 which should be 1000
要说它将值1000赋予项目而不是total_value。但是当我改变两个短语的顺序时,它正常工作,如上所示。请有人帮我这个。我是Ruby和编程的新手。原谅我破碎的英语...
项目背景:
# Greed is a dice game where you roll up to five dice to accumulate
# points. The following "score" function will be used to calculate the
# score of a single roll of the dice.
#
# A greed roll is scored as follows:
#
# * A set of three ones is 1000 points
#
# * A set of three numbers (other than ones) is worth 100 times the
# number. (e.g. three fives is 500 points).
#
# * A one (that is not part of a set of three) is worth 100 points.
#
# * A five (that is not part of a set of three) is worth 50 points.
#
# * Everything else is worth 0 points.
#
#
# Examples:
#
# score([1,1,1,5,1]) => 1150 points
# score([2,3,4,6,2]) => 0 points
# score([3,4,5,3,3]) => 350 points
# score([1,5,1,2,4]) => 250 points
#
# More scoring examples are given in the tests below:
#
# Your goal is to write the score method.
答案 0 :(得分:0)
.map方法根据短语的顺序返回值,而不是变量的名称。我很困惑......
或多或少,是的。块只返回最后一个表达式的值,非常类似于方法。
如果你有:
count.map! do |item|
item - 3
total_score = 1000
end
然后评估为total_score = 1000
的{{1}}是块的返回值。
如果你有:
1000
然后count.map! do |item|
total_score = 1000
item - 3
end
是块的返回值。
item - 3
依次创建一个包含块中值的新数组。
答案 1 :(得分:0)
这是另一种方式:
def three_of_a_kind(dice, count)
count * (dice == 1 ? 1000 : 100 * dice)
end
def no_set(dice, count)
case dice
when 1
count * 100
when 5
count * 50
else
0
end
end
def score(rolls)
rolls.group_by(&:itself).map do |dice, throws|
n = throws.size
three_of_a_kind(dice, n / 3) + no_set(dice, n % 3)
end.inject(:+)
end
p score([1, 1, 1, 5, 1]) == 1150
p score([2, 3, 4, 6, 2]) == 0
p score([3, 4, 5, 3, 3]) == 350
p score([1, 5, 1, 2, 4]) == 250
顺便说一下:
side = 6
count = Array.new
side.times{count << 0}
只是:
Array.new(6){ 0 }