What is the return value of the following Ruby code?

str = "abc".freeze

str += "def" # => ???

The correct answer is

It raises FrozenError

"abcdef"

"abc"

nil

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

String#+ does not modify self. Indeed, it simply returns a new instance of String that is reassigned to str.

str = "abc".freeze

str.object_id # => 17320

str = str + "def" # => "abcdef"

str.object_id # => 30460

So the first frozen string assigned to str is replaced by the new String returned by String#+.

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 ©