9

I'm curious. Is it surprising that the snippet below yields a FrozenError? The magic comment # frozen_string_literal: true is not present.

n = nil
s = n.to_s
s.force_encoding('UTF-8')
2
  • What version of Ruby? And which line triggers the error? Aug 20, 2020 at 0:02
  • I am confused. Why would the presence or absence of # frozen_string_literal: true matter? Aug 20, 2020 at 0:09

1 Answer 1

13

This was added in Ruby 2.7 -- It's documented explicitly in the release notes.

Module#name, true.to_s, false.to_s, and nil.to_s now always return a frozen String. The returned String is always the same for a given object. [Experimental] [Feature #16150]

The linked issue has additional reasoning behind the change:

Much of the time when a user calls to_s, they are just looking for a simple string representation to display or to interpolate into another string. In my brief exploration, the result of to_s is rarely mutated directly.

It seems that we could save a lot of objects by providing a way to explicitly request a frozen string. ... This would reduce string allocations dramatically when applied to many common to_s calls.

In summary, it reduces object allocations, which reduces garbage collection overhead, which improves performance.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.