FlapsMack FlapsMack - 3 months ago 7
Ruby Question

How to sum ordinal values of letters in strings/keys of a hash, then sum all the 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.

EDIT
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

This will do what you require:

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

A breakdown...

games.keys
  #=> ["Mario", "Ico", "Tetris"]
games.keys.join
  #=> "MarioIcoTetris"     
games.keys.join.chars
  #=> ["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

Even Better...

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

games.keys.join.chars.map(&:ord).inject(:+) #=> 1422

Just for fun...

Here's another way where we define a method within the String class then apply the method to each key before summing up all the ordinal-sums of the keys:

class String
  def sumord
    chars.map(&:ord).inject(:+) 
  end
end

games.keys.map(&:sumord).inject(:+) #=> 1422