Can you set a default value for a hash using Literal Notation?


#1



Can you set a default value for a hash using Literal Notation?


Replace this line with your code.


#2

Referring to,

no_nil_hash = Hash.new("Not found")

?
I don't think there is a literal way to do this. The above hash can be populated with an arbitrary number of keys, each with a starting value, "Not found". If we try to do this literally, it will mean writing the value out for each member of the hash. There won't really be a default in the normal sense. Am I not reading your question correctly?


#3

@mtf for the example you gave us no_nil_hash = Hash.new("Not found") has been taught to us by Ruby as hash constructor notation. Ruby taught us there are 2 ways to create hashes, the other being hash literal notation. Can we do it that way?

ie)

new_hash**("Not found"???)** {
"key1" => "value1"
"key2" => "value2"
"key3" => "value3"
}


#4

new_hash("default") = {
    "line" -> "1"
}

Console error:

(eval): (eval): compile error (SyntaxError)
(eval): syntax error, unexpected '=', expecting $end
new_hash("default") = {
                     ^

And,

new_hash("default") {
    
}

Error

(eval):4: undefined method `new_hash' for main:Object (NoMethodError)

This should let us conclude that there is no way to set a default without the constructor function. For a dynamic hash, the constructor would be the way to go. It allows new keys to be added on the fly, and gives them all the same starting value, such as 0 for keys that are going to be accumulators.

frequencies = new.Hash(0)
frequencies['and'] += 1
puts frequencies['and']    # 1