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
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#+
.
Check out our courses, mini-projects, and 300+ resources on RubyCademy
RubyCademy ©