Search code examples
ruby

Ruby array to hash: each element the key and derive value from it


I have an array of strings, and want to make a hash out of it. Each element of the array will be the key, and I want to make the value being computed from that key. Is there a Ruby way of doing this?

For example:

['a','b'] to convert to {'a'=>'A','b'=>'B'}


Solution

  • Ruby's each_with_object method is a neat way of doing what you want

    ['a', 'b'].each_with_object({}) { |k, h| h[k] = k.upcase }