3 ms·
The literals would be identified at parse time. fooLit = "foo" fooVar = "f".concat("o").concat("o") This would have fooLit be frozen at parse time. I
by shagie 1y ago
The literals would be identified at parse time.
fooLit = "foo"
fooVar = "f".concat("o").concat("o")
This would have fooLit be frozen at parse time. In this situation there would be "foo", "f", and "o" as frozen strings; and fooLit and fooVar would be two different strings since fooVar was created at runtime.
Creating a string that happens to be present in the frozen strings wouldn't create a new one.
- meisel 1y agoGot it, so this could not be extended to non-literal strings
- shagie 1y agoYou can freeze strings that are created at runtime. irb(main):001> str = "f".concat("o").concat("o") => "foo" irb(main):002> str.frozen? => false irb(main):003> str.freeze => "foo" irb(main):004> str.frozen? => true irb(main):005> str = str.concat("bar") (irb):5:in 'String#concat': can't modify frozen #<Class:#<String:0x000000015807ec58>>: "foo" (FrozenError) from (irb):5:in '<main>' from <internal:kernel>:168:in 'Kernel#loop' from /opt/homebrew/Cellar/ruby/3.4.4/lib/ruby/gems/3.4.0/gems/irb-1.14.3/exe/irb:9:in '<top (required)>' from /opt/homebrew/opt/ruby/bin/irb:25:in 'Kernel#load' from /opt/homebrew/opt/ruby/bin/irb:25:in '<main>'