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"
end