# frozen_string_literal: true # sample-frozen-string.rb: what the frozen_string_literal magic comment does. # Free sample from 99helpers.com/file-types/rb # Run: ruby sample-frozen-string.rb # Try it without line 1 too: on Ruby 3.4 and later, `ruby -W:deprecated` # then warns at step 1 instead of raising, because literals are "chilled". # 1. With the comment, string literals are frozen: changing one in place # raises FrozenError. greeting = "Hello" begin greeting << ", world" rescue FrozenError => e puts "1. #{e.class}: #{e.message}" end # 2. Methods that return a new string still work on frozen strings. puts "2. #{greeting + ', world'} / #{greeting.upcase} / frozen? #{greeting.frozen?}" # 3. Unary plus (or dup) gives a mutable copy when you need one. buffer = +"Hello" buffer << ", world" puts "3. #{buffer} / frozen? #{buffer.frozen?}" # 4. Interpolated strings are never frozen (since Ruby 3.0). name = "Ada" puts "4. frozen? #{"Hi #{name}".frozen?}" # 5. Identical frozen literals are the same object, which saves memory. puts "5. same object? #{'abc'.equal?('abc')}"