Reputation: 1347
final_sub_hash = {}
<% workers.each do |work| %>
<% sub_hash = {} %>
<% sub_hash = {:name => work['name'], :gender => work['gender']} %>
<% final_sub_hash.update(sub_hash) %>
<% end %>
What I am trying to do is append the values of sub_hash to final_sub_hash but I am not able to figure out how can I do that. Please help me find a solution.
Upvotes: 0
Views: 857
Reputation: 52268
I arrived here from a search for how to add a hash to a hash. In case anyone else wonders the same, here's a nice example
# Create a hash
h = {a: 1, b: 2}
# => {:a=>1, :b=>2}
# Add a hash to the existing hash
h.store(:c, {i: 10, ii: 20})
# > {:a=>1, :b=>2, :c=>{:i=>10, :ii=>20}}
The new key can be a symbol (like :c
, as above), but it could also be a string:
h.store("c", {i: 10, ii: 20})
# => {:a=>1, :b=>2, "c"=>{:i=>10, :ii=>20}}
Upvotes: 1
Reputation: 26
hash.store(key, value)
stores a key-value pair in hash
.
Example:
hash #=> {"a"=>1, "b"=>2, "c"=>55}
hash["d"] = 30 #=> 30
hash #=> {"a"=>1, "b"=>2, "c"=>55, "d"=>30}
What you are trying to do is a list.
Example:
works = []
work.append(hash) #=> [ {"a"=>1, "b"=>2, "c"=>55, "d"=>30} ]
Upvotes: 1