在Ruby中如何在没有键的情况下获取哈希值?

时间:2019-09-17 11:56:40

标签: ruby

def hand_score(hand)
  cards = {"A" => 4, "K" => 3, "Q" => 2, "J" => 1}
  score = 0

  hand.each_char do |char|
    score += cards[char.upcase]
  end
  return score
end

puts hand_score("AQAJ") #=> 11
puts hand_score("jJka") #=> 9

cards[char.upcase]如何 计算哈希中的数字而不是字符串?

cards{"A" => 4}

cards[char]如何求出数字4而不是字母“ A”?

1 个答案:

答案 0 :(得分:3)

Ruby Hash可以按预期工作,但也许您不理解所提供的代码。

cards = {"A" => 4, "K" => 3, "Q" => 2, "J" => 1}

在此示例中,字母是键,数字是值。要获取值,您可以像这样调用键:

cards['A'] # this will return 4

hand.each_char # this is iterating over each character that is passed as a single string argument to your method.

 hand.each_char do |char| # char is just the iterator assigned inside the loop 
   score += cards[char.upcase] 
 end

可以使用变量代替循环内发生的字符串。

char = 'a'
cards[char] # this will return nil because the keys were defined in upper case.
cards[char.upcase] # this will return 4 because the key is found when it is upper case.

有关更多信息,请参见documentation on Hash class