FlapsMack FlapsMack - 1 year ago 107
Ruby Question

Hash iteration keys

I have this hash:

games = {"Mario" => "SNES", "Ico" => "PS2", "Tetris" => "Gameboy"}

I want to make a method that will convert the keys to integers and then add all of the keys in the hash together and return a single integer

I looked up some methods on rubydocs and came across the string method .ord which converts letters to their numerical values.
I know I will want to split('') the keys I'm just not sure how to get it all to work.

Sorry for the confusion. What I am looking for, is to split the keys into individual letters/characters, convert them with .ord to their numerical ordinal, add all of the numbers together and return the sum.

Answer Source

This will do what you require

games.keys.join.chars.map { |c| c.ord }.inject(:+) #=> 1422

A breakdown...

  #=> ["Mario", "Ico", "Tetris"]
  #=> "MarioIcoTetris"     
  #=> ["M", "a", "r", "i", "o", "I", "c", "o", "T", "e", "t", "r", "i", "s"]
games.keys.join.chars.map { |c| c.ord }
  #=> [77, 97, 114, 105, 111, 73, 99, 111, 84, 101, 116, 114, 105, 115] 
games.keys.join.chars.map { |c| c.ord }.inject(:+)
  #=> 1422

If you wanted to be a bit fancier you could also write:

games.keys.join.chars.map(&:ord).inject(:+) #=> 1422
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download