在 Ruby 中使用 << 将键/值对附加到散列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19756139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append key/value pair to hash with << in Ruby
提问by jcarpio
In Ruby, one can append values to existing arrays using <<:
在 Ruby 中,可以使用 << 将值附加到现有数组:
a = []
a << "foo"
but, can you also append key/value pairs to an existing hash?
但是,您还可以将键/值对附加到现有的哈希吗?
h = {}
h << :key "bar"
I know you can do:
我知道你可以这样做:
h[:key] = ""
h[:key] << "bar"
but that's not I want.
但这不是我想要的。
Thanks.
谢谢。
回答by Mark Thomas
Since hashes aren't inherently ordered, there isn't a notion of appending. Ruby hashes since 1.9 maintain insertion order, however. Here are the ways to add new key/value pairs.
由于哈希本身不是有序的,因此没有附加的概念。然而,自 1.9 以来的 Ruby 哈希保持插入顺序。以下是添加新键/值对的方法。
The simplest solution is
最简单的解决方案是
h[:key] = "bar"
If you want a method, use store:
如果你想要一个方法,请使用store:
h.store(:key, "bar")
If you really, really want to use a "shovel" operator (<<), it is actually appending to the value of the hash as an array, and you must specify the key:
如果您真的、真的想使用“铲子”运算符 ( <<),它实际上是以数组的形式附加到哈希值,并且您必须指定键:
h[:key] << "bar"
The above only works when the key exists. To append a new key, you have to initialize the hash with a default value, which you can do like this:
以上仅当密钥存在时才有效。要附加新键,您必须使用默认值初始化散列,您可以这样做:
h = Hash.new {|h, k| h[k] = ''}
h[:key] << "bar"
You may be tempted to monkey patch Hash to include a shovel operator that works in the way you've written:
您可能会想修改 Hash 以包含一个以您编写的方式工作的 shovel 运算符:
class Hash
def <<(k,v)
self.store(k,v)
end
end
However, this doesn't inherit the "syntactic sugar" applied to the shovel operator in other contexts:
但是,这不会继承在其他上下文中应用于 shovel 运算符的“语法糖”:
h << :key, "bar" #doesn't work
h.<< :key, "bar" #works
回答by PericlesTheo
No, I don't think you can append key/value pairs. The only thing closestthat I am aware of is using the storemethod:
不,我认为您不能附加键/值对。我所知道的唯一最接近的是使用该store方法:
h = {}
h.store("key", "value")
回答by Michael Durrant
Perhaps you want Hash#merge ?
也许你想要 Hash#merge ?
1.9.3p194 :015 > h={}
=> {}
1.9.3p194 :016 > h.merge(:key => 'bar')
=> {:key=>"bar"}
1.9.3p194 :017 >
If you want to change the array in place use merge!
如果您想就地更改数组,请使用 merge!
1.9.3p194 :016 > h.merge!(:key => 'bar')
=> {:key=>"bar"}
回答by kayleeFrye_onDeck
Similar as they are, merge!and storetreat existinghashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!'s key: "value"syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.
与它们相似,merge!并根据键名store对现有哈希进行不同的处理,因此会影响您的偏好。除了从语法的角度来看,merge!的key: "value"语法与 JavaScript 和 Python 非常匹配。我个人一直讨厌逗号分隔的键值对。
hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash
{:key=>"value"}
{:key=>"value"}
hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash
{:key=>"value", "key"=>"value"}
{:key=>"value", "key"=>"value"}
To get the shovel operator <<working, I would advise using Mark Thomas's answer.
为了让铲子操作员<<工作,我建议使用Mark Thomas的答案。
回答by Caner ?akmak
I had to do a similar thing but I needed to add values with same keys. When I use merge or update I can't push values with same keys. So I had to use array of hashes.
我不得不做类似的事情,但我需要使用相同的键添加值。当我使用合并或更新时,我无法使用相同的键推送值。所以我不得不使用哈希数组。
my_hash_static = {:header =>{:company => 'xx', :usercode => 'xx', :password => 'xx',
:type=> 'n:n', :msgheader => from}, :body=>[]}
my_hash_dynamic = {:mp=>{:msg=>message, :no=>phones} }
my_hash_full = my_hash_static[:body].push my_hash_dynamic

