Ruby-on-rails 如何检查哈希中是否存在特定值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9012388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if specific value is present in a hash?
提问by tyronegcarter
I'm using Rails and I have a hash object. I want to search the hash for a specific value. I don't know the keys associated with that value.
我正在使用 Rails 并且我有一个哈希对象。我想在哈希中搜索特定值。我不知道与该值关联的键。
How do I check if a specific value is present in a hash? Also, how do I find the key associated with that specific value?
如何检查哈希中是否存在特定值?另外,如何找到与该特定值关联的键?
回答by rkb
Hash includes Enumerable, so you can use the many methods on that module to traverse the hash. It also has this handy method:
Hash 包括Enumerable,因此您可以使用该模块上的许多方法来遍历哈希。它还有这个方便的方法:
hash.has_value?(value_you_seek)
To find the key associated with that value:
要查找与该值关联的键:
hash.key(value_you_seek)
This API documentation for Ruby (1.9.2)should be helpful.
Ruby (1.9.2) 的这个API 文档应该会有所帮助。
回答by Anton Orel
The simplest way to check multiple values are present in a hash is:
检查散列中是否存在多个值的最简单方法是:
h = { a: :b, c: :d }
h.values_at(:a, :c).all? #=> true
h.values_at(:a, :x).all? #=> false
In case you need to check also on blank values in Rails with ActiveSupport:
如果您还需要使用 ActiveSupport 检查 Rails 中的空白值:
h.values_at(:a, :c).all?(&:present?)
or
或者
h.values_at(:a, :c).none?(&:blank?)
The same in Ruby without ActiveSupport could be done by passing a block:
在没有 ActiveSupport 的 Ruby 中,同样可以通过传递一个块来完成:
h.values_at(:a, :c).all? { |i| i && !i.empty? }
回答by Val Akkapeddi
回答by d1jhoni1b
Imagine you have the following Arrayof hashes
想象一下你有以下Array哈希值
available_sports = [{name:'baseball', label:'MLB Baseball'},{name:'tackle_football', label:'NFL Football'}]
available_sports = [{name:'baseball', label:'MLB Baseball'},{name:'tackle_football', label:'NFL Football'}]
Doing something like this will do the trick
做这样的事情会成功
available_sports.any? {|h| h['name'] == 'basketball'}
available_sports.any? {|h| h['name'] == 'basketball'}
=> false
=> false
available_sports.any? {|h| h['name'] == 'tackle_football'}
available_sports.any? {|h| h['name'] == 'tackle_football'}
=> true
=> true
回答by siame
回答by Subhash Chandra
回答by Fellow Stranger
回答by hidace
An even shorter version that you could use would be hash.values
您可以使用的更短的版本是 hash.values

