Singleton method là method định nghĩa chỉ trên 1 object cụ thể, không ảnh hưởng các instance khác của cùng class.
ruby
str = "hello"
def str.shout
upcase + "!!!"
end
str.shout # => "HELLO!!!"
"world".shout # => NoMethodErrorMọi object trong Ruby có một eigenclass (còn gọi singleton class / metaclass) — class ẩn chứa singleton methods của object đó.
Class methods (def self.method) thực ra là singleton methods trên object class.
ruby
class Foo
def self.bar = "class method" # singleton method trên object Foo
end
# Mở eigenclass trực tiếp
class << Foo
def baz = "also class method"
endA singleton method is defined on a single specific object and does not affect other instances of the same class.
ruby
str = "hello"
def str.shout
upcase + "!!!"
end
str.shout # => "HELLO!!!"
"world".shout # => NoMethodErrorEvery Ruby object has a hidden eigenclass (also called singleton class / metaclass) that stores the object's singleton methods.
Class methods (def self.method) are in fact singleton methods defined on the class object itself.
ruby
class Foo
def self.bar = "class method" # singleton method on the Foo object
end
# Open eigenclass directly
class << Foo
def baz = "also class method"
end