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.
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.
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.
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.
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.
Hash
's key?
method tells you whether a given key is present or not.
session.key?("user")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With