ruby学习笔记(8)-"静态方法的4种写法"与"单例方法的2种写法"

简介: #静态方法的4种写法 class Test def Test.StaticMethod1 puts "Test.StaticMethod1" end def self.
#静态方法的4种写法
class Test
  def Test.StaticMethod1
    puts "Test.StaticMethod1"
  end
  
  def self.StaticMethod2
    puts "Test.StaticMethod2"
  end
  
  class << Test
    def StaticMethod3
      puts "Test.StaticMethod3"
    end
  end
  
  class << self
    def StaticMethod4
      puts "Test.StaticMethod4"
    end
  end
end
  
Test.StaticMethod1
Test.StaticMethod2
Test.StaticMethod3
Test.StaticMethod4

 

#单例方法的2种写法

class Test
  def method1
    puts "method1"
  end
end

t1 = Test.new

def t1.singleMethod1
  puts "t1.singleMethod1"
end

class << t1
  def singleMethod2
    puts "t1.singleMethod2"
  end
end

t2 = Test.new

t1.method1
t2.method1
t1.singleMethod1
t1.singleMethod2
#t2.singleMethod1 #将报错
#t2.singleMethod2 #将报错
目录
相关文章
|
移动开发 索引
|
Ruby 网络架构 数据安全/隐私保护
|
Ruby Windows 开发工具
ruby语言学习笔记2
ruby学习笔记2  (摘自《ruby程序设计语言教程(中文版)》.pdf,全书25页) 1.同一个问题ruby有多个解决方案,途径 ruby之父:松本行弘(Matz),1993年创立 ruby的偶数发行版为稳定版 圆括号在方法调用中是可选的。
810 0