freeze
In this page:
freeze
.freeze makes an object immutable, so any attempt to modify it afterward raises a FrozenError. String literals are mutable by default in Ruby (unlike some languages), so freeze is used explicitly when you want to guarantee a string never changes. Freezing is also commonly applied to constants to prevent accidental mutation.
Note: # frozen_string_literal: true as the first line of a file makes every string literal in it frozen by default.
Example: freeze
name = "Alice".freeze
puts name.frozen?
begin
name << " Smith"
rescue => e
puts "Error: #{e.class}"
end
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: