Ruby:如何在哈希结构中过滤以获得“1”的所有键?

时间:2021-12-15 16:20:12

I want to find some elegant way to achieve this. Maybe like follwing:

我想找到一些优雅的方法来实现这一目标。也许像下面这样:

hash={"1"=>"1","2"=>"2"}
r=[]
hash.each do |k,v|
    if k!="1"
       r<<k
    end
end
puts r

Any better way to achieve this?

有没有更好的方法实现这一目标

4 个解决方案

#1


12  

You can use "array difference":

你可以使用“数组差异”:

hash.keys - ['1']
#=> ["2"]

#2


3  

puts r = hash.keys.select { |i| i != "1" }

#3


1  

Here's one way:

这是一种方式:

r = hash.select { |k,v,| k != "1" }
puts r

Hope this helps,
Ben

希望这有帮助,本

#4


0  

hash.reject{|k,v| k == "1"}

I like reject over select with a negative test because it's more readable. "Reject values where X == '1' is true" versus "collect values where x != '1' is true".

我喜欢拒绝选择负面测试,因为它更具可读性。 “拒绝X =='1'的值为真”与“收集值,其中x!='1'为真”。

#1


12  

You can use "array difference":

你可以使用“数组差异”:

hash.keys - ['1']
#=> ["2"]

#2


3  

puts r = hash.keys.select { |i| i != "1" }

#3


1  

Here's one way:

这是一种方式:

r = hash.select { |k,v,| k != "1" }
puts r

Hope this helps,
Ben

希望这有帮助,本

#4


0  

hash.reject{|k,v| k == "1"}

I like reject over select with a negative test because it's more readable. "Reject values where X == '1' is true" versus "collect values where x != '1' is true".

我喜欢拒绝选择负面测试,因为它更具可读性。 “拒绝X =='1'的值为真”与“收集值,其中x!='1'为真”。