How to check if a specific key is present in a hash or not?
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.
Hash
's key?
method tells you whether a given key is present or not.
session.key?("user")
While Hash#has_key?
gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?
.
hash.key?(some_key)
In latest Ruby versions Hash instance has a key?
method:
{a: 1}.key?(:a)
=> true
Be sure to use the symbol key or a string key depending on what you have in your hash:
{'a' => 2}.key?(:a)
=> false
链接地址: http://www.djcxy.com/p/60948.html
上一篇: do..end与红宝石块的花括号