FlapsMack FlapsMack - 1 year ago 71
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
which converts letters to their numerical values.
I know I will want to
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
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

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

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