[ruby] 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.

This question is related to ruby data-structures associative-array

The answer is


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

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)

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


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

Another way is here

hash = {one: 1, two: 2}

hash.member?(:one)
#=> true

hash.member?(:five)
#=> false

In Rails 5, the has_key? method checks if key exists in hash. The syntax to use it is:

YourHash.has_key? :yourkey

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

Examples related to ruby

Uninitialized Constant MessagesController Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Ruby - ignore "exit" in code Empty brackets '[]' appearing when using .where find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? How to update Ruby with Homebrew?

Examples related to data-structures

Program to find largest and second largest number in array golang why don't we have a set datastructure How to initialize a vector with fixed length in R C compiling - "undefined reference to"? List of all unique characters in a string? Binary Search Tree - Java Implementation How to clone object in C++ ? Or Is there another solution? How to check queue length in Python Difference between "Complete binary tree", "strict binary tree","full binary Tree"? Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

Examples related to associative-array

How to insert a new key value pair in array in php? Rename a dictionary key How to update specific key's value in an associative array in PHP? Is there a way to create key-value pairs in Bash script? PHP combine two associative arrays into one array Are there dictionaries in php? Display array values in PHP Adding an item to an associative array Extract subset of key-value pairs from Python dictionary object? Java associative-array