添加一对新的哈希,我做:

{:a => 1, :b => 2}.merge!({:c => 3})   #=> {:a => 1, :b => 2, :c => 3}

是否有类似的方法从哈希中删除键?

如此:

{:a => 1, :b => 2}.reject! { |k| k == :a }   #=> {:b => 2}

但我希望有这样的东西:

{:a => 1, :b => 2}.delete!(:a)   #=> {:b => 2}

重要的是,返回值将是剩余的散列,所以我可以这样做:

foo(my_hash.reject! { |k| k == my_key })

在一行里。


当前回答

这也可以工作:hash[hey] = nil

其他回答

试试except!方法。

{:a => 1, :b => 2}.except!(:a)   #=> {:b => 2}

有许多方法可以从散列中删除键并在Ruby中获取剩余的散列。

.slice => It will return selected keys and not delete them from the original hash. Use slice! if you want to remove the keys permanently else use simple slice. 2.2.2 :074 > hash = {"one"=>1, "two"=>2, "three"=>3} => {"one"=>1, "two"=>2, "three"=>3} 2.2.2 :075 > hash.slice("one","two") => {"one"=>1, "two"=>2} 2.2.2 :076 > hash => {"one"=>1, "two"=>2, "three"=>3} .delete => It will delete the selected keys from the original hash(it can accept only one key and not more than one). 2.2.2 :094 > hash = {"one"=>1, "two"=>2, "three"=>3} => {"one"=>1, "two"=>2, "three"=>3} 2.2.2 :095 > hash.delete("one") => 1 2.2.2 :096 > hash => {"two"=>2, "three"=>3} .except => It will return the remaining keys but not delete anything from the original hash. Use except! if you want to remove the keys permanently else use simple except. 2.2.2 :097 > hash = {"one"=>1, "two"=>2, "three"=>3} => {"one"=>1, "two"=>2, "three"=>3} 2.2.2 :098 > hash.except("one","two") => {"three"=>3} 2.2.2 :099 > hash => {"one"=>1, "two"=>2, "three"=>3} .delete_if => In case you need to remove a key based on a value. It will obviously remove the matching keys from the original hash. 2.2.2 :115 > hash = {"one"=>1, "two"=>2, "three"=>3, "one_again"=>1} => {"one"=>1, "two"=>2, "three"=>3, "one_again"=>1} 2.2.2 :116 > value = 1 => 1 2.2.2 :117 > hash.delete_if { |k,v| v == value } => {"two"=>2, "three"=>3} 2.2.2 :118 > hash => {"two"=>2, "three"=>3} .compact => It is used to remove all nil values from the hash. Use compact! if you want to remove the nil values permanently else use simple compact. 2.2.2 :119 > hash = {"one"=>1, "two"=>2, "three"=>3, "nothing"=>nil, "no_value"=>nil} => {"one"=>1, "two"=>2, "three"=>3, "nothing"=>nil, "no_value"=>nil} 2.2.2 :120 > hash.compact => {"one"=>1, "two"=>2, "three"=>3}

基于Ruby 2.2.2的结果。

为什么不直接使用:

hash.delete(key)

哈希现在是您正在寻找的“剩余哈希”。

如果delete返回哈希的delete对,那就太好了。 我这样做:

hash = {a: 1, b: 2, c: 3}
{b: hash.delete(:b)} # => {:b=>2}
hash  # => {:a=>1, :c=>3} 

这是一种单行的方式,但可读性不强。建议用两行代替。

use_remaining_hash_for_something(Proc.new { hash.delete(:key); hash }.call)