symbolize_keys

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 }

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

The provided Rails code initializes a hash h with two key-value pairs:

  1. :key with a value of 42.
  2. '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à!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©