Ruby object mặc định mutable (có thể sửa sau khi tạo). Trừ:
- Integer, Float, Symbol — immutable theo thiết kế ngôn ngữ (không có setter).
- Bất kỳ object nào đã freeze.
- String literal khi bật # frozen_string_literal: true (mặc định của Rubocop).
ruby
str = +"mutable" # unary + tạo mutable string (Ruby 2.3+)
str << " OK" # => "mutable OK"
frozen_str = -"immutable" # unary - tạo frozen string
frozen_str << "!" # => FrozenError
:sym << "x" # NoMethodError — Symbol không có <<
42.frozen? # => true — Integer luôn frozenHình dung: Integer/Symbol như hằng số toán học — giá trị 5 không thể "bị sửa", chỉ có thể tạo 6 mới.
Ruby objects are mutable by default. Exceptions:
- Integer, Float, Symbol — immutable by language design (no setters).
- Any object after calling freeze.
- String literals when # frozen_string_literal: true is active (Rubocop default).
ruby
str = +"mutable"
str << " OK" # => "mutable OK"
frozen_str = -"immutable"
frozen_str << "!" # => FrozenError
:sym << "x" # NoMethodError
42.frozen? # => true — Integer is always frozenMental model: Integer/Symbol behave like mathematical constants — you cannot modify 5; you can only produce 6.