2

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
    Regarding _"nil keys"_ – you should distinguish between "nil" and "missing". It's perfectly fine for a hash to have `nil` as a key e.g. `h1 = { nil => 123 }` and also as a value e.g. `h2 = { foo: nil }`. Neither `h1[nil]` nor `h2[:foo]` would trigger the default value. Only a _missing_ key would do so. – Stefan May 20 '21 at 10:12

2 Answers2

5

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"
spickermann
  • 100,941
  • 9
  • 101
  • 131
3

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

dcangulo
  • 1,888
  • 1
  • 16
  • 48