Convert Array to Hash in Ruby
This article will shortly discuss the solution to convert the following array:
['key1', 'value1', 'key2', 'value2']
into a hash with the following format:
{ 'key1' => 'value1', 'key2' => 'value2' }
Use Array.to_h
to Convert Array to Hash in Ruby
Ruby version 2.1.10 introduced a new method, to_h
on the array, which interprets a 2-element array into a hash.
Code:
[['key1', 'value1'], ['key2', 'value2']].to_h
We first need to convert our original array to a 2-element array.
Code:
['key1', 'value1', 'key2', 'value2'].each_slice(2).to_a
Output:
[["key1", "value1"], ["key2", "value2"]]
Combine everything with 1 line version.
Code:
['key1', 'value1', 'key2', 'value2'].each_slice(2).to_a.to_h
Output:
{ "key1"=>"value1", "key2"=>"value2" }
Use Hash::[]
to Convert Array to Hash in Ruby
Hash::[]
accepts a list of arguments. The number of this list should be even, or an error will be raised.
Hash::[]
converts the list into a hash, where odd arguments will be the keys, and even arguments will be the values.
Code:
Hash['key1', 'value1', 'key2', 'value2']
Output:
{"key1"=>"value1", "key2"=>"value2"}
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.