Ruby frozen_string_literal

Content:

This may be wellknown among Ruby programmers, but I (as a non-Ruby-programmer) was surprised when I saw it mentioned on LInkedIn.

C:\Work\Ruby>type strfun.rb
s1 = "ABC"
s2 = s1
printf "#{s1} #{s2}\n"
s1[1] = "X"
printf "#{s1} #{s2}\n"

C:\Work\Ruby>ruby strfun.rb
ABC ABC
AXC AXC

C:\Work\Ruby>type strnofun.rb
# frozen_string_literal: true
s1 = "ABC"
s2 = s1
printf "#{s1} #{s2}\n"
s1[1] = "X"
printf "#{s1} #{s2}\n"

C:\Work\Ruby>ruby strnofun.rb
ABC ABC
strnofun.rb:5:in `[]=': can't modify frozen String: "ABC" (FrozenError)
        from strnofun.rb:5:in `<main>'

C:\Work\Ruby>type strfun2.rb
def f(s)
    s[1] = "X"
    print "#{s}\n"
end

f("ABC")

C:\Work\Ruby>ruby strfun2.rb
AXC

C:\Work\Ruby>type strnofun2.rb
# frozen_string_literal: true

def f(s)
    s[1] = "X"
    print "#{s}\n"
end

f("ABC")

C:\Work\Ruby>ruby strnofun2.rb
strnofun2.rb:4:in `[]=': can't modify frozen String: "ABC" (FrozenError)
        from strnofun2.rb:4:in `f'
        from strnofun2.rb:8:in `<main>'

I think one should always use '# frozen_string_literal: true' as the default behavior is a bit 1970ish.

Comments: