319 views
What's the return value of this Ruby 3 code?
h = { a: 1, b: 2 } h.replace(h.invert) h[:a] # => ???
The correct answer is
2
:b
It raises NoMethodError
nil
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
h = { a: 1, b: 2 }
Here, h
is a hash with two key-value pairs:
:a
maps to value 1
:b
maps to value 2
invert
Method:The invert
method swaps the keys and values in the hash. For h = { a: 1, b: 2 }
, calling invert
results in:
h.invert # => { 1 => :a, 2 => :b }
After inversion:
:a
(which mapped to 1
) is now the value, and 1
becomes the key.:b
(which mapped to 2
) is now the value, and 2
becomes the key.replace
Method:
h.replace(h.invert) # => { 1 => :a, 2 => :b }
The replace
method completely replaces the contents of the original hash h
with the contents of another hash.
In this case, the original h
(which was { a: 1, b: 2 }
) is replaced by the result of h.invert
(which is { 1 => :a, 2 => :b }
).
Now, the original key :a
no longer exists in the hash because it was replaced by 1
in the inversion process.
So, when you try to access h[:a]
, it returns nil
because there is no key :a
in the new hash.
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©