Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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'}

like image 665
lulalala Avatar asked Feb 24 '12 15:02

lulalala


People also ask

How do you turn an Array into a Hash in Ruby?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

How do you push values into an Array of Hash in Ruby?

Creating an array of hashes You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.

How do I get the Hash value in Ruby?

Convert the key from a string to a symbol, and do a lookup in the hash. Rails uses this class called HashWithIndifferentAccess that proves to be very useful in such cases.

What is the difference between a Hash and an Array in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key.


3 Answers

You can:

a = ['a', 'b']
Hash[a.map {|v| [v,v.upcase]}]
like image 71
Ricardo Acras Avatar answered Oct 06 '22 18:10

Ricardo Acras


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 }
like image 7
aidan Avatar answered Oct 06 '22 18:10

aidan


%w{a b c}.reduce({}){|a,v| a[v] = v.upcase; a}
like image 22
brad Avatar answered Oct 06 '22 18:10

brad