[ruby]单例类 singleton class

  • 单例类定义被用于定义对象的专属实例方法。
# 初始化变量
str1 = 'Ruby'   # String的一个对象
str2 = 'Ruby'  # String的一个对象
str3 = 'ruby'  # String的一个对象
str4 = [1,2]  # Array的一个对象
str5 = {a:6}  # Hash的一个对象
str6 = 1  # Numeric的一个对象
str7 = Numeric.new
  • 在类中定义类方法, class << 类名 ~ end这种写法的类定义称为单例类定义,单例类定义中定义的方法称为单例方法 singleton method
class Hello
  class << Hello   # class << self 一样
    def hello
       "hello #{self}"
     end
   end
end
p Hello.hello # =>  "hello Hello"
# 接上面代码 
a = Hello.new
class << a #单例类
  def hello 
    "hello #{self}"
  end
end
p a.hello #=> "hello #<Hello:0x00007fd3aa171760>"
  • 不能用未定义的常量,或者变量去定义单例类
class << Hi  # class << hi
    def hello
       "

猜你喜欢

转载自blog.csdn.net/qq_41037744/article/details/119975726