Ruby Language Conversion to and from Arrays


Example

Hashes can be freely converted to and from arrays. Converting a hash of key/value pairs into an array will produce an array containing nested arrays for pair:

{ :a => 1, :b => 2 }.to_a # => [[:a, 1], [:b, 2]]

In the opposite direction a Hash can be created from an array of the same format:

[[:x, 3], [:y, 4]].to_h # => { :x => 3, :y => 4 }

Similarly, Hashes can be initialized using Hash[] and a list of alternating keys and values:

Hash[:a, 1, :b, 2] # => { :a => 1, :b => 2 }

Or from an array of arrays with two values each:

Hash[ [[:x, 3], [:y, 4]] ] # => { :x => 3, :y => 4 }

Hashes can be converted back to an Array of alternating keys and values using flatten():

{ :a => 1, :b => 2 }.flatten # => [:a, 1, :b, 2]

The easy conversion to and from an array allows Hash to work well with many Enumerable methods such as collect and zip:

Hash[('a'..'z').collect{ |c| [c, c.upcase] }] # => { 'a' => 'A', 'b' => 'B', ... }

people = ['Alice', 'Bob', 'Eve']
height = [5.7, 6.0, 4.9]
Hash[people.zip(height)] # => { 'Alice' => 5.7, 'Bob' => '6.0', 'Eve' => 4.9 }