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:
via_hash_literal = {"default value for nil key"}but this is causing an error:syntax error, unexpected '}', expecting =>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"}via_hash_literal = {nil => "default value for nil key"}does not throw an error but thenputs 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.
The
{}syntax to generate a new hash in Ruby doesn't support setting a default. But you can useHash#default=to set an default too: