I know there are other questions similar such as:
But the answers aren’t fully satisfactory.
I have:
ruby-1.9.2-p290 :001 > a=Hash.new
=> {}
ruby-1.9.2-p290 :002 > a['one']="hello"
=> "hello"
ruby-1.9.2-p290 :006 > defined?(a['one']['some']).nil?
=> false
ruby-1.9.2-p290 :007 > a['one']['some'].nil?
=> true
It seems like:
if a['one']['some'].nil?
a['one']['some']=Array.new
end
would be sufficient. Is this correct? Would this be correct for any data type? Is defined? needed in this case?
thx
You seem to be confusing two concepts. One is if a variable is defined, and another is if a Hash key is defined. Since a hash is, at some point, a variable, then it must be defined.
Something can be a key and
nilat the same time, this is valid. There is no concept of defined or undefined for a Hash. It is all about if the key exists or not.The only reason to test with
.nil?is to distinguish between the two possible non-true values:nilandfalse. If you will never be usingfalsein that context, then calling.nil?is unnecessarily verbose. In other words,if (x.nil?)is equivalent toif (x)providedxwill never be literallyfalse.What you probably want to employ is the
||=pattern that will assign something if the existing value isnilorfalse:Update: Edited according to remarks by Bruce.