Comment by shagie

3 days 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.

Got it, so this could not be extended to non-literal strings

  • You 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>'