我是新来的我在做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]
score([1,1,1]) # score([1,1,1]) = 101000 which should be 1000
也就是说,它将值1000赋予item而不是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.
3条答案
按热度按时间irtuqstp1#
.map方法根据短语的顺序返回值,而不是变量的名称。我很困惑。
或多或少是的。块只是返回最后一个表达式的值,很像方法。
如果您有:
那么
total_score = 1000
,它的计算结果是1000
,是块的返回值。如果您有:
那么
item - 3
是块的返回值。map!
又创建了一个新数组,其中包含块中的值。bmp9r5qi2#
还有一种方法:
顺便说一下:
就是:
lmvvr0a83#