How to check if a specific key is present in a hash or not?

531

54

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.

Mohit Jain

Posted 2010-12-24T22:02:13.947

Reputation: 21 261

Answers

798

Hash's key? method tells you whether a given key is present or not.

session.key?("user")

sepp2k

Posted 2010-12-24T22:02:13.947

Reputation: 290 410

nice: "string" accessor works for JSON.parse parsed objects, too :) – Bijan – 2016-08-08T14:32:51.937

2This doesn't work for me, the :user method worked instead – Akash Agarwal – 2017-03-22T20:10:07.003

261

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)

Bozhidar Batsov

Posted 2010-12-24T22:02:13.947

Reputation: 45 383

1Nice reference to that change request and subsequent response from Matz. – Joshua Pinter – 2015-09-10T12:20:18.847

Does anybody know for sure? – codeforester – 2017-01-13T09:40:10.527

31

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

installero

Posted 2010-12-24T22:02:13.947

Reputation: 5 521

2

Apprently existed as early as Ruby 1.6: http://ruby-doc.com/docs/ProgrammingRuby/html/ref_c_hash.html#Hash.key_qm (perhaps earlier, dunno where to check documented)

– Beni Cherniavsky-Paskin – 2016-06-28T14:36:55.120

26

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

G.B

Posted 2010-12-24T22:02:13.947

Reputation: 2 698

5If you are using Rails, you can use Hash#with_indifferent_access to avoid this; both :my_key and "my_key" will point to the same record – Devon Parsons – 2016-04-06T14:07:21.217

4

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

Deepak Mahakale

Posted 2010-12-24T22:02:13.947

Reputation: 14 104