Singleton Method in Ruby

类的单件方法(类方法)

类可以有单件方法,类的单件方法可以被继承。

class People
  def self.kind
    "human"
  end
end

class Student < People
end

p People.kind   # => "human"
p Student.kind  # => "human"

对象的单件方法

对象可以有单件方法,只是这个对象本身所有的方法

普通方法

class C
  def talk
    puts "Hi!"
  end
end

c = C.new
c.talk
# Output: Hi!

单件方法定义

obj = Object.new
def obj.talk
  puts "Hi!"
end
obj.talk
#377
#Output: Hi!

使用instance_eval()定义单件方法

s1, s2 = "abc", "def"
s1.instance_eval do
  def swoosh!
    reverse
  end
end

s1.swoosh!  # => "cba"
s2.respond_to?(:swoosh!)   # => false

instance_eval()的含义是:“我想修改self”

Every object has two classes:

  • The class of which it’s an instance
  • Its singleton class

相关文章: