Kasem777
Kasem777

Reputation: 865

In Ruby how to get the value in hash without the key?

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

How does cards[char.upcase] evaluate to the number in the hash not to the string?

cards{"A" => 4}

How does cards[char] evaluate to the number 4 not to the letter "A" ??

Upvotes: 0

Views: 682

Answers (1)

lacostenycoder
lacostenycoder

Reputation: 11226

Ruby Hash is working as expected but perhaps you don't understand the code you've provided.

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

In this example the letters ARE the keys and the numbers are the values. To get a value, you call the key like this:

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

A variable can be used instead of the string which is what's happening inside the loop.

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.

For more see documentation on Hash class

Upvotes: 3

Related Questions