# frozen_string_literal: true đặt ở đầu file khiến mọi string literal trong file đó trở thành frozen và được deduplicated — cùng một string literal chỉ tạo 1 object duy nhất trong memory.
ruby
# frozen_string_literal: true
str1 = "hello"
str2 = "hello"
str1.equal?(str2) # => true — cùng 1 object!
str1.frozen? # => true
str1 << " world" # => FrozenError
# Tạo mutable string khi cần:
mutable = +"mutable string" # unary + thêm vào prefix
mutable << "!"Lợi ích hiệu năng: mỗi lần gọi method/loop không tạo mới string literal → giảm GC pressure đáng kể trong code xử lý nhiều string.
- Rubocop enforce magic comment này bằng cop
Style/FrozenStringLiteralComment. - Ruby 4.0 dự kiến bật frozen string literal mặc định.