Ruby: How to set a default value for nil keys on a hash created via hash literal notation?

1.2k Views Asked by At

In a free Ruby course I'm working through, I was shown the way to create a default value for a hash via constructor. And it looks like so:

no_nil_hash = Hash.new("default value for nil key")
puts no_nil_hash["non_existing_key"]

Which prints: default value for nil key

How would I go about this via the way of hash literal notation?

Did not find any answers via google and here are my futile attempts so far:

  1. via_hash_literal = {"default value for nil key"} but this is causing an error: syntax error, unexpected '}', expecting =>
  2. via_hash_literal = {=> "default value for nil key"} causing more errors: syntax error, unexpected =>, expecting '}' via_hash_literal = { => "default value for nil key"} syntax error, unexpected '}', expecting end-of-input ...=> "default value for nil key"}
  3. via_hash_literal = {nil => "default value for nil key"} does not throw an error but then puts via_hash_literal["non_existing_key"] does not print the default key: default value for nil key, instead I get an empty row of line.
2

There are 2 best solutions below

0
On BEST ANSWER

The {} syntax to generate a new hash in Ruby doesn't support setting a default. But you can use Hash#default= to set an default too:

hash = {}
hash.default = "default value"

hash[:foo]
#=> "default value"
0
On

It can be written as the following:

no_nil_hash = {}
no_nil_hash.default = "default value for nil key"
puts no_nil_hash["non_existing_key"]

Result in IRB:

irb(main):001:0> no_nil_hash = {}
=> {}
irb(main):002:0> no_nil_hash.default = "default value for nil key"
=> "default value for nil key"
irb(main):003:0> no_nil_hash["non_existing_key"]
=> "default value for nil key"

Read more: https://docs.ruby-lang.org/en/2.0.0/Hash.html