Pierre.Sassoulas Pierre.Sassoulas - 7 months ago 12
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 = {
    1=>0,
    2=>42,
    }
    MY_HASH.default = -1



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

MY_HASH = {
1=>0,
2=>42,
}.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

You can use update:

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

Or you can use Hash#merge.

Comments