Ruby Tuesday – Array#to_h

Today’s Ruby Tuesday is on Array#to_h.

Array#to_h will turn an Array of two element Arrays into a Hash where each two element Array represents a key value pair in the new Hash.

[[1, :a], [2, :b]].to_h
# => {1=>:a, 2=>:b}
[["cat", "meow"], ["dog", "woof"], ["mouse", "squeak"]].to_h
# => {"cat"=>"meow", "dog"=>"woof", "mouse"=>"squeak"}

If called on an Array that is not an Array of Arrays, you get a TypeError.

[1, 2, 3, 4].to_h
# TypeError: wrong element type Fixnum at 0 (expected array)
# from (pry):4:in `to_h'

If called on an Array that is an Array of Arrays, but the nested Arrays are not of length two, an ArgumentError is raised.

[[1, 2, 3], [2, 3, 4]].to_h
# ArgumentError: wrong array length at 0 (expected 2, was 3)
# from (pry):5:in `to_h'

The items in the nested arrays can be anything, even more Arrays, but those arrays will just be used as is.

[[1, [2, 3]], [[:a, :b], [3, 4]]].to_h
# => {1=>[2, 3], [:a, :b]=>[3, 4]}

–Proctor