Edit:
There are tons of great answers here till I do not know which to select as the "answer". Based on a comment suggestion, this question should be marked as "off topic". Hence, I'm sorry but I will not choosing an answer and I shall leave this here in case someone else has the same question I have.
Is there a difference between:
(1)
a = {
:x => 1
}
And
(2)
b = {
:x => 1,
:y => nil
}
Given that for (1), a[:y] returns nil
And for (2), b[:y] returns nil
as well
The only difference I see is that when I output:
(1)
{
:x => 1
}
And (2)
{
:x => 1
:y => nil
}
There are several differences. Let me describe two, so you know where to look:
Hash#fetch
raises error (or calls a block if it's provided) if key is not present:
a.fetch(:y)
# >> KeyError: key not found: :y
> a.fetch(:y){ "100" }
# => "100"
b.fetch(:y)
# => nil
b.fetch(:y){ "100" }
# => nil
Hash#map
(and all other iterators) takes the key with nil
value into account:
a.map{|k, v| [k, v]}
# => [[:x, 1]]
b.map{|k, v| [k, v]}
# => [[:x, 1], [:y, nil]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With