Is there any way simpler than
if hash.key?('a')
hash['a']['b'] = 'c'
else
hash['a'] = {}
hash['a']['b'] = 'c'
end
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The easiest way is to construct your Hash with a block argument:
This form for
newcreates a new empty Hash as the default value. You don’t want this:as that will use the exact same hash for all default entries.
Also, as Phrogz notes, you can make the auto-vivified hashes auto-vivify using
default_proc:UPDATE: I think I should clarify my warning against
Hash.new({ }). When you say this:That’s pretty much like saying this:
And then, when you access
hto assign something ash[:k][:m] = y, it behaves as though you did this:And then, if you
h[:k2][:n] = z, you’ll end up assigningh.default[:n] = z. Note thathstill says thath.has_key?(:k)is false.However, when you say this:
Everything will work out okay because you will never modified
h[k]in place here, you’ll only read a value fromh(which will use the default if necessary) or assign a new value toh.