ruby merge array of hashes into one hash
a.reduce Hash.new, :merge
ruby merge array of hashes into one hash
a.reduce Hash.new, :merge
ruby merge array of hashes into one hash
a.inject(:merge)
#=> {:a=>:b, :c=>:d}
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{...})
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us