如何检查哈希中是否存在特定密钥?
我想检查会话哈希中是否存在“用户”密钥。我该怎么做?
请注意,我不想检查键的值是否为零。我只想检查“用户”密钥是否存在。
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" key is present.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
Hash
的key?
方法告诉您给定的密钥是否存在。Hash
'skey?
method tells you whether a given key is present or not.虽然
Hash#has_key?
完成了工作,正如 Matz 所说 此处,它已被弃用,取而代之的是Hash#key?
。While
Hash#has_key?
gets the job done, as Matz notes here, it has been deprecated in favour ofHash#key?
.哈希实例有一个
密钥?
方法:
请务必使用符号键或字符串键,具体取决于哈希中的内容:
Hash instance has a
key?
method:Be sure to use the symbol key or a string key depending on what you have in your hash:
现在已经很晚了,但最好应该使用符号作为键:
但是在创建哈希时,如果您传递字符串作为键,那么它将在键中搜索字符串。
但是在创建哈希时,您将符号作为键传递,然后传递 has_key 吗?将使用符号搜索键。
如果您使用Rails,则可以使用
Hash#with_in Different_access
来避免这种情况;hash[:my_key]
和hash["my_key"]
都将指向同一条记录It is very late but preferably symbols should be used as key:
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.
If you are using Rails, you can use
Hash#with_indifferent_access
to avoid this; bothhash[:my_key]
andhash["my_key"]
will point to the same record另一种方法在这里
Another way is here
您始终可以使用
Hash#key?
来检查密钥是否存在于哈希中。如果没有,它会返回
false
You can always use
Hash#key?
to check if the key is present in a hash or not.If not it will return you
false
在 Rails 5 中,has_key? 方法检查 key 是否存在于哈希中。使用它的语法是:
In Rails 5, the has_key? method checks if key exists in hash. The syntax to use it is: