Take the 2-minute tour ×

I am working on rails and I want to check whether user key is present or not in session hash. How can I check this?

PS: I don't want to check whether this value is nil or not. I want to check weather user KEY exists or not.

share|improve this question
You meant "hash[map]" when you said "array" (arrays don't have keys and session in rails is a hash (with indifferent access - though that's irrelevant to the question), not an array). I fixed that for you. –  sepp2k Dec 24 '10 at 22:08
@sepp2k thnks... –  Mohit Jain Dec 25 '10 at 1:25
add comment

3 Answers

up vote 256 down vote accepted

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

share|improve this answer
Here is the latest reference in an online Ruby documentation resource: ruby-doc.org/core-1.9.3/Hash.html#method-i-has_key-3F –  Phil DD Jun 26 '13 at 13:27
While this does technically work, it's deprecated. See the other answer for a more up-to-date solution. –  scubbo Apr 11 at 12:41
add comment

While Hash#has_key? gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?.

share|improve this answer
add comment

It is very late but preferably symbols should be used as key:

my_hash = {}
my_hash[:my_key] = 'value'

 => false 
 => true 

my_hash2 = {}
my_hash2['my_key'] = 'value'

 => true 
 => 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.

share|improve this answer
add comment

Your Answer


