Can anyone show me a ruby way of checking if a key exists in a hash and if it does not then give it a default value. I'm assuming there is a one liner using unless to do this but I'm not sure what to use.
Checking if key exists using the get() method The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None. Using this method we can pass a key and check if a key exists in the python dictionary.
get() method returns a default value if the key is missing. However, if the key is not found when you use dict[key] , KeyError exception is raised.
How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.
If you already have a hash, you can do this:
h.fetch(key, "default value")
Or you exploit the fact that a non-existing key will return nil
:
h[key] || "default value"
To create hashes with default values it depends on what you want to do exactly.
Independent of key and will not be stored:
h = Hash.new("foo") h[1] #=> "foo" h #=> {}
Dependent on the key and will be stored:
h = Hash.new { |h, k| h[k] = k * k } h[2] #=> 4 h #=> {2=>4}
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