Ruby-on-rails 如何检查特定键是否存在于哈希中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4528506/
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 a specific key is present in a hash or not?
提问by Mohit Jain
I want to check whether the "user" key is present or not in the session hash. How can I do this?
我想检查会话哈希中是否存在“用户”键。我怎样才能做到这一点?
Note that I don't want to check whether the key's value is nil or not. I just want to check whether the "user" keyis present.
请注意,我不想检查键的值是否为 nil。我只想检查“用户”键是否存在。
回答by sepp2k
Hash's key?method tells you whether a given key is present or not.
Hash的key?方法告诉您给定的键是否存在。
session.key?("user")
回答by Bozhidar Batsov
回答by installero
回答by G.B
It is very late but preferably symbols should be used as key:
很晚了,但最好使用符号作为键:
my_hash = {}
my_hash[:my_key] = 'value'
my_hash.has_key?("my_key")
=> false
my_hash.has_key?("my_key".to_sym)
=> true
my_hash2 = {}
my_hash2['my_key'] = 'value'
my_hash2.has_key?("my_key")
=> true
my_hash2.has_key?("my_key".to_sym)
=> false
But when creating hash if you pass string as key then it will search for the string in keys.
但是在创建哈希时,如果您将字符串作为键传递,那么它将在键中搜索字符串。
But when creating hash you pass symbol as key then has_key? will search the keys by using symbol.
但是在创建哈希时,您将符号作为键传递,然后是 has_key?将使用符号搜索键。
If you are using Rails, you can use Hash#with_indifferent_accessto avoid this; both hash[:my_key]and hash["my_key"]will point to the same record
如果您使用的是 Rails,则可以使用Hash#with_indifferent_access来避免这种情况;双方hash[:my_key]并hash["my_key"]会指向相同的记录
回答by Deepak Mahakale
You can always use Hash#key?to check if the key is present in a hash or not.
您始终可以使用Hash#key?来检查密钥是否存在于散列中。
If not it will return you false
如果没有它会返回你 false
hash = { one: 1, two:2 }
hash.key?(:one)
#=> true
hash.key?(:four)
#=> false
回答by Arvind singh
Another way is here
另一种方式在这里
hash = {one: 1, two: 2}
hash.member?(:one)
#=> true
hash.member?(:five)
#=> false
回答by BinaryMan
In Rails 5, the has_key?method checks if key exists in hash. The syntax to use it is:
在 Rails 5 中,has_key? 方法检查哈希中是否存在键。使用它的语法是:
YourHash.has_key? :yourkey

