Pierre.Sassoulas Pierre.Sassoulas - 2 years ago 79
Ruby Question

Declaring a Hash as a Constant with a default value in Ruby in one line

My goal is to use a Hash with a default value as a class constant. To do this it seems to me that I must initialise a Hash in one line as a constant with pre-defined value and a default value.

According to the Ruby documentation, I can set a default value in two way :

  • In the constructor then by adding value as follow :

    MY_HASH = Hash.new(-1)
    MY_HASH[1] = 0
    MY_HASH[2] = 42

  • By adding values first then setting the default value later :

    MY_HASH = {
    MY_HASH.default = -1

I tried to do it in one line like this, but it does not work :

}.default = -1

#It's the same as :
MY_HASH = -1

Is there a way to declare a Hash with a default value in one line ?

Answer Source

You can use update:

MY_HASH = Hash.new(-1).update(1=>0, 2=>42)
#=> 0
#=> -1

Or you can use Hash#merge.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download