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 教程 之 Ruby 方法 2
Ruby return 语句
130 0
|
C语言 C++ Ruby
|
Ruby
Ruby 教程 之 Ruby 方法 3
可变数量的参数
136 1
|
应用服务中间件 Apache nginx
深入探索研究Ruby CGI方法
【10月更文挑战第2天】
129 4
|
应用服务中间件 Apache nginx
探索研究Ruby CGI方法
【9月更文挑战第2天】
127 4
|
开发者 测试技术 Android开发
Xamarin 开发者的五大常见问题及解决方案:从环境搭建到性能优化,全面解析高效跨平台应用开发的技巧与代码实例
【8月更文挑战第31天】Xamarin 开发者常遇问题及解决方案覆盖环境搭建至应用发布全流程,助新手克服技术难关。首先需正确安装配置 Visual Studio 及 Xamarin 支持,设置 iOS/Android 测试环境。利用 Xamarin.Forms 和 XAML 实现高效跨平台开发,共享 UI 和业务逻辑代码。针对性能优化,采取减少 UI 更新、缓存计算结果等措施,复杂问题则借助 Xamarin Profiler 分析。
185 0