When should actually freeze work?


(Morris, Chris) #1

s = "abc"
s.freeze
s.frozen ? # >> true
s = “123” # doesn’t throw a can’t modify frozen string. why ?
s.frozen? # >> false (but I thought I told it to freeze :slight_smile:

You’re not modifying the string “abc”, you’re re-assigning s to a new string
altogether:

irb(main):001:0> s = “abc”
"abc"
irb(main):002:0> s.id
22437268
irb(main):004:0> s = "123"
"123"
irb(main):005:0> s.id
22408828

Try a method like reverse! on a frozen string which is self-modifying:

irb(main):007:0> s.freeze
"123"
irb(main):008:0> s.frozen?
true
irb(main):009:0> s.reverse!
TypeError: can’t modify frozen string
from (irb):9:in `reverse!'
from (irb):9

Chris