Answers for "convert array of hashes to hash ruby"

3

ruby merge array of hashes into one hash

a.reduce Hash.new, :merge
Posted by: Guest on July-31-2020
2

ruby merge array of hashes into one hash

a.inject(:merge)
#=> {:a=>:b, :c=>:d}
Posted by: Guest on July-31-2020
1

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{...})
Posted by: Guest on May-20-2021

Code answers related to "convert array of hashes to hash ruby"

Browse Popular Code Answers by Language