如何在一行中向Hash添加元素?

时间:2014-08-06 19:51:02

标签: ruby

我有一个哈希,里面有一些数据。为简单起见,我想在一行中添加更多元素。这就是我想要做的事情:

hash = add_items_to_it(hash, { alpha: 1, beta: 2 })

有可能吗?

2 个答案:

答案 0 :(得分:2)

使用Hash#merge!

hash.merge! { alpha: 1, beta: 2 }

阅读文档:

arup@linux-wzza:~/Ruby> ri Hash#merge!

= Hash#merge!

(from ruby site)
------------------------------------------------------------------------------
  hsh.merge!(other_hash)                                 -> hsh
  hsh.merge!(other_hash){|key, oldval, newval| block}    -> hsh

------------------------------------------------------------------------------

Adds the contents of other_hash to hsh.  If no block
is specified, entries with duplicate keys are overwritten with the values from
other_hash, otherwise the value of each duplicate key is
determined by calling the block with the key, its value in hsh and its
value in other_hash.

  h1 = { "a" => 100, "b" => 200 }
  h2 = { "b" => 254, "c" => 300 }
  h1.merge!(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}

  h1 = { "a" => 100, "b" => 200 }
  h2 = { "b" => 254, "c" => 300 }
  h1.merge!(h2) { |key, v1, v2| v1 }
                  #=> {"a"=>100, "b"=>200, "c"=>300}


lines 1-25/25 (END)

答案 1 :(得分:1)

您正在寻找Hash#merge

hash = { one: 1, two: 2 }
#=> {:one=>1, :two=>2}
hash = hash.merge({ alpha: 1, beta: 2 })
#=> {:one=>1, :two=>2, :alpha=>1, :beta=>2}