2444 views
What's the return value of the following Rails 7 code?
h = { key: 42, 'key' => 84 } h.symbolize_keys # => ???
The correct answer is
{ "key" => 42 }
{ key: 42 }
{ key: 84 }
{ "key" => 84 }
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
The provided Rails code initializes a hash h
with two key-value pairs:
:key
with a value of 42
.'key'
(a string) with a value of 84
.Then, the method symbolize_keys
is invoked on the hash h
.
This method is a Rails extension to the Hash
class, which converts keys in the hash to symbols.
However, since there's already a key :key
in the hash, the symbolize_keys
method doesn't change it.
Instead, it converts the string key 'key'
to a symbol :key
.
So, after invoking symbolize_keys
, the hash h
effectively becomes:
{ :key => 42, :key => 84 }
Since duplicate keys are not allowed in a hash in Ruby, the value associated with the second occurrence of :key
(which is 84
) overwrites the previous value (42
).
Thus, the final output of h.symbolize_keys
is
{ key: 84 }
.
Voilà!
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©