确定哈希是否包含一组键中的任何键?

发布于 2024-11-05 08:43:11 字数 268 浏览 0 评论 0原文

您知道一种漂亮的 ruby​​ 方法来查找哈希是否具有某些键之一吗?

h = {:a => 1, :c => 3, :d => 4}
# keys to find are :a, :b or :e

我知道我可以做:

h.key?(:a) || h.key?(:b) || h.key?(:e)

但我想知道是否有更漂亮的方法来做到这一点! :)

多谢 !

Do you know a pretty ruby way to find if an hash has one of some keys ?

h = {:a => 1, :c => 3, :d => 4}
# keys to find are :a, :b or :e

I know that I can do a :

h.key?(:a) || h.key?(:b) || h.key?(:e)

But I was wondering if there was a prettier way to do it ! :)

Thanks a lot !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

花开雨落又逢春i 2024-11-12 08:43:11

考虑 Enumerable.any?

[:a, :b, :e].any? {|k| h.key?(k)}

来自IRB:

>> h = {:a => 1}; [:x].any? {|k| h.key?(k)}                    
=> false                                                                
>> h = {:a => 1}; [:x, :a].any? {|k| h.key?(k)}                
=> true

快乐编码。

Consider Enumerable.any?

[:a, :b, :e].any? {|k| h.key?(k)}

From IRB:

>> h = {:a => 1}; [:x].any? {|k| h.key?(k)}                    
=> false                                                                
>> h = {:a => 1}; [:x, :a].any? {|k| h.key?(k)}                
=> true

Happy coding.

女中豪杰 2024-11-12 08:43:11

以下是从数组中获取所有匹配键的方法:

> {:a => 1, :c => 3, :d => 4}.keys & [:a, :d, :e]
 => [:a, :d] 

如果您想要一个布尔值(遵循安德鲁的建议):

> ({:a => 1, :c => 3, :d => 4}.keys & [:a, :d, :e]).empty?
 => false 
> ({:a => 1, :c => 3, :d => 4}.keys & [:f, :e]).empty?
 => true 

Here is how you get all of the matching keys from an array:

> {:a => 1, :c => 3, :d => 4}.keys & [:a, :d, :e]
 => [:a, :d] 

and if you want a boolean (following Andrew's suggestion):

> ({:a => 1, :c => 3, :d => 4}.keys & [:a, :d, :e]).empty?
 => false 
> ({:a => 1, :c => 3, :d => 4}.keys & [:f, :e]).empty?
 => true 
最笨的告白 2024-11-12 08:43:11

我会做这样的事情:

[:a, :b, :e].any?{ |val| h.key?(val) } 

I would do something like this:

[:a, :b, :e].any?{ |val| h.key?(val) } 
蓝眸 2024-11-12 08:43:11
h.select{|k| [:b, :w, :e].include?(k) }.empty?
h.select{|k| [:a, :w, :e].include?(k) }.empty?

然后你会得到匹配键的哈希值(键和值)作为返回(没有空?)

h.select{|k| [:b, :w, :e].include?(k) }.empty?
h.select{|k| [:a, :w, :e].include?(k) }.empty?

And you get hash (key and value) of matching key in return (without empty?)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文