ruby %i[ to array of hashes code example

Example: ruby on rails turn array into hash

1d_array = ["a", 1, "b", 2]
2d_array = [ ["a", 1], ["b", 2] ]

1d_hash = Hash(*1d_array) # result: {"a"=>1, "b"=>2}
2d_hash = 2d_array.to_h # result: {"a"=>1, "b"=>2}
# You can also write it as 2d_hash = Hash(2d_array)

# Note that both result in the same hash structure
# The `.to_h` notation is useful for chainging off other methods
# For example: User.pluck(:id, :name).to_h

# If you need a more complex conversion you can use .map
complex_array = [ ["a", 1, "alpha"], ["b", 2, "beta"] ]
complex_hash = complex_array.map{|k, v1, v2| [k, {"order": v1, "greek": v2}]}.to_h
# Again you can write it as Hash(complex_array.map{...})

Tags:

Ruby Example