Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between {:x => 1} and {:x => 1, :y => nil} in ruby?

Tags:

null

ruby

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
}
like image 303
Kiong Avatar asked Jan 26 '23 01:01

Kiong


1 Answers

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]]
like image 166
mrzasa Avatar answered Jan 28 '23 14:01

mrzasa