Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 812
Mohit Jain Avatar asked Dec 24 '10 22:12

Mohit Jain


People also ask

How do you check if a key already exists in a hash Ruby?

We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.

How do you check if a key exists in a hash in Perl?

The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.

How do you get the key of a hash in Ruby?

Ruby | Hash key() functionHash#key() is a Hash class method which gives the key value corresponding to the value. If value doesn't exist then return nil.

What is a key-value hash?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.


2 Answers

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

session.key?("user") 
like image 160
sepp2k Avatar answered Sep 19 '22 09:09

sepp2k


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) 
like image 24
Bozhidar Batsov Avatar answered Sep 19 '22 09:09

Bozhidar Batsov