[英]add hash to hashes in ruby
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.我想做的是 append sub_hash 到 final_sub_hash 的值,但我无法弄清楚我该怎么做。 Please help me find a solution.
请帮我找到解决办法。
hash.store(key, value)
stores a key-value pair in hash
. hash.store(key, value)
将键值对存储在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} ]
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我是通过搜索如何将 hash 添加到 hash 而来到这里的。如果其他人也有同样的疑问,这里有一个很好的例子
# 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:新密钥可以是一个符号(如
:c
,如上所述),但也可以是一个字符串:
h.store("c", {i: 10, ii: 20})
# => {:a=>1, :b=>2, "c"=>{:i=>10, :ii=>20}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.