从Rails中的哈希中删除多个键和值对

时间:2022-02-05 18:18:06
number = {:a => 1, :b => 2, :c => 3, :d => 4}

upon evaluation of certain condition i want to delete key-value pair of a,b,c

在评估某些条件时,我想删除a,b,c的键值对

3 个解决方案

#1


17  

number.delete "A"
number.delete "B"
number.delete "C"

Or, less performant but more terse:

或者,性能较差但更简洁:

number.reject! {|k, v| %w"A B C".include? k }

#2


13  

or, more performant than second Chris' solution but shorter than first:

或者,比第二克里斯的解决方案更高效,但比第一个更短:

%w"A B C".each{|v| number.delete(v)}

#3


3  

ActiveSupport that is a part of Rails comes with several built-in methods can help you to achieve your goal.

ActiveSupport是Rails的一部分,附带了几个内置方法可以帮助您实现目标。

If you just want to delete some key-value pairs, you can use Hash#except!

如果您只想删除一些键值对,可以使用Hash#除外!

number.except!(:a, :b, :c)

If you want to keep the original hash, then use Hash#except

如果你想保留原始哈希值,那么使用哈希#除外

new_hash = number.except!(:a, :b, :c)

new_hash # => {:d=>4}
number # => {:a=>1, :b=>2, :c=>3, :d=>4}

You also can go with Rails-free way:

您也可以使用无Rails方式:

new_hash = number.dup.tap do |hash|
  %i[a b c].each {|key| hash.delete(key)}
end

new_hash # => {:d=>4}
number # => {:a=>1, :b=>2, :c=>3, :d=>4}

P.S.: the last code example is very slow, I'm just providing it as an alternative.

P.S。:最后一个代码示例非常慢,我只是提供它作为替代。

#1


17  

number.delete "A"
number.delete "B"
number.delete "C"

Or, less performant but more terse:

或者,性能较差但更简洁:

number.reject! {|k, v| %w"A B C".include? k }

#2


13  

or, more performant than second Chris' solution but shorter than first:

或者,比第二克里斯的解决方案更高效,但比第一个更短:

%w"A B C".each{|v| number.delete(v)}

#3


3  

ActiveSupport that is a part of Rails comes with several built-in methods can help you to achieve your goal.

ActiveSupport是Rails的一部分,附带了几个内置方法可以帮助您实现目标。

If you just want to delete some key-value pairs, you can use Hash#except!

如果您只想删除一些键值对,可以使用Hash#除外!

number.except!(:a, :b, :c)

If you want to keep the original hash, then use Hash#except

如果你想保留原始哈希值,那么使用哈希#除外

new_hash = number.except!(:a, :b, :c)

new_hash # => {:d=>4}
number # => {:a=>1, :b=>2, :c=>3, :d=>4}

You also can go with Rails-free way:

您也可以使用无Rails方式:

new_hash = number.dup.tap do |hash|
  %i[a b c].each {|key| hash.delete(key)}
end

new_hash # => {:d=>4}
number # => {:a=>1, :b=>2, :c=>3, :d=>4}

P.S.: the last code example is very slow, I'm just providing it as an alternative.

P.S。:最后一个代码示例非常慢,我只是提供它作为替代。