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 ?
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With