Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

hash

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 ?

like image 383
Pierre.Sassoulas Avatar asked May 03 '16 18:05

Pierre.Sassoulas


2 Answers

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.

like image 139
Ilya Avatar answered Nov 01 '22 20:11

Ilya


Here are two other solutions.

MY_HASH = { 1=>0, 2=>42 }.tap { |h| h.default = -1 }
MY_HASH[1]      #=> 0
MY_HASH[529326] #=> -1

MY_HASH = ->(key) { { 1=>0, 2=>42 }.fetch(key, -1) }
MY_HASH[1]      #=>  0
MY_HASH[529326] #=> -1
like image 44
Cary Swoveland Avatar answered Nov 01 '22 19:11

Cary Swoveland