Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If key does not exist create default value

Tags:

ruby

hash

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.

like image 949
Steve Avatar asked Feb 02 '12 07:02

Steve


People also ask

What if a key is not present in dictionary python?

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.

What does the get () method return when a key is not found in the 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?

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.


1 Answers

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} 
like image 120
Michael Kohl Avatar answered Sep 28 '22 13:09

Michael Kohl