Ruby Hashes and Default Value Tutorial

In this section, we will learn how Hashes can be used as the default values for methods’ parameters.

Note: we’re assuming you’re already familiar with Ruby Hashes.

What is the default value in Ruby Hashes?

When working with hashes, if you call a key in a hash object and it didn’t have it, you’ll get the value nil as a result!

Basically, the value nil is the default value and it will be returned whenever we try to access a key in a hash object that does not exist there.

But this is the default behavior of Ruby hash objects and we can change this default value to something else.

This is done by creating a new hash object using the Hash class and setting a value as the argument of the `new` method. This value then will be used as the default value to be returned instead of the value nil whenever we call a key in that hash object and the key doesn’t exist.

How to set a default value for Ruby Hashes?

As you can see, the default value we put as the argument of the new method will be considered as the default value for calling keys that don’t exist in the target hash object.

Example: setting default values for Ruby hashes

person ="Does not exist")

person[:first_name] = "John"

person[:last_name] = "Doe"

puts person[:first_name], person[:last_name], person[:age], person[:salary]




Does not exist

Does not exist

How does default value work for Ruby Hashes?

In the last example, you can see that the two keys `first_name` and `last_name` exist in the hash object and so we get their values on the output stream.

But then the other two keys `age` and `salary` didn’t exist in this hash object and so when we called for these keys, we got the default value as a result!

Ruby Hash Default Value Note:

Note that calling a key that doesn’t exist in a hash object in order to get its value won’t register that key in the target hash object, though! This means for calling such type of keys, we only get the default value without those keys being registered in the target hash object.


Top Technologies