726 views
What's the return value of the following Ruby code?
h = Hash.new([]) h[:a] << 42 h[:b] # => ???
The correct answer is
[]
[nil]
[42]
nil
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
Let's break down the provided Ruby code and then demonstrate how h.default
changes from []
to [42]
after h[:a] << 42
is executed.
First, let's understand the code:
h = Hash.new([]) h[:a] << 42 h[:b] # => [42]
1- h = Hash.new([])
This line creates a new hash called h
with a default value of an empty array []
.
This means that if you try to access a key in the hash that doesn't exist, it will return an empty array by default.
2- h[:a] << 42
This line accesses the key :a
in the hash h
and appends the value 42
to the array associated with that key.
However, the interesting thing here is that since the default value for h
is an empty array []
, if the key :a
didn't exist previously, it will create the key and assign an empty array as its value, then append 42
to that array.
3- h[:b] # => [42]
This line accesses the key :b
in the hash h
. Since :b
hasn't been explicitly defined before, it uses the default value of the hash, which is the same empty array shared across all keys.
However, since we appended 42
to the array associated with :a
in the previous step, the default value now contains [42]
.
To demonstrate that h.default
changes from []
to [42]
, let's print out h.default
before and after appending 42
to h[:a]
:
h = Hash.new([]) h.default # => [] h[:a] << 42 h.default # => [42]
Voilà!
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©