Techioz Blog

Ruby Koans : About_Scoring_Project (正確には、.map メソッドを使用したイテレータ)

概要

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

つまり、total_value ではなく item に値 1000 が与えられています。ただし、上記のように 2 つのフレーズの順序を変更すると、正しく動作します。誰かこれを手伝ってくれませんか。私は 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.

解決策

多かれ少なかれ、そうです。ブロックは、メソッドとほぼ同じように、最後に評価された式の値を単に返すだけです。

あなたが持っている場合:

count.map! do |item|
  item - 3
  total_score = 1000
end

total_score = 1000 は、1000 と評価され、ブロックの戻り値になります。

あなたが持っている場合:

count.map! do |item|
  total_score = 1000
  item - 3
end

item - 3 はブロックの戻り値です。

地図!次に、ブロックの値を含む新しい配列を作成します。