How to check if a specific key is present in a hash or not?
RubyData StructuresAssociative ArrayRuby Problem Overview
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.
Ruby Solutions
Solution 1 - Ruby
Hash
's key?
method tells you whether a given key is present or not.
session.key?("user")
Solution 2 - Ruby
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)
Solution 3 - Ruby
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
Solution 4 - Ruby
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.
If you are using Rails, you can use Hash#with_indifferent_access
to avoid this; both hash[:my_key]
and hash["my_key"]
will point to the same record
Solution 5 - Ruby
Another way is here
hash = {one: 1, two: 2}
hash.member?(:one)
#=> true
hash.member?(:five)
#=> false
Solution 6 - Ruby
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
hash = { one: 1, two:2 }
hash.key?(:one)
#=> true
hash.key?(:four)
#=> false
Solution 7 - Ruby
In Rails 5, the has_key? method checks if key exists in hash. The syntax to use it is:
YourHash.has_key? :yourkey
Solution 8 - Ruby
You can use hash.keys.include?(key)
irb(main):001:0> hash = {"pot" => 1, "tot" => 2, "not" => 3}
=> {"pot"=>1, "tot"=>2, "not"=>3}
irb(main):002:0> key = "not"
=> "not"
irb(main):003:0> hash.keys.include?(key)
=> true