- # 定义类方法
- class Demo
- @instvariable=100 #实例变量
# 类变量,需要在使用之前初始化,否则会报错,也就是在get之前要先set,可以写方法set,也可以在 # initialize中做初始化的工作
- @@classvariable=200
- def initialize
- end
- # class method
- def Demo.method1
- end
- # class method
- def self.method2
- end
- # class method
- class << self
- def method3
- end
- end
- # instance method
- def instmethod
- end
- def pubmethod
- end
- def primethod
- end
- def protmethod
- end
- public :pubmethod
- private :primethod
- protected :protmethod
- end
- demo=Demo.new
- # list all method, include class method and instance method
- Demo.methods
- # list all method which user defined, include class method and instance mehtod
- Demo.methods(false)
- # list all instance method
- Demo.instance_methods
- # list all instance method which user defined
- Demo.instance_methods(false)
- # list all instance variable
- Demo.instance_variables
- # list all class variables Demo.class_variables
- singleton
- class MyLogger
- private_class_method :new #将new这个类方法私有化
- @@logger=nil
- def self.create
- @@logger =new unless @@logger
- @@logger
- end
- end
- MyLogger.create
实例变量访问器instance variable accessor
- class Demo
- attr_access :name
- end
- demo=Demo.new
- demo.name="andyshi"
- puts demo.name
读写访问器
- attr_reader :name
- attr_writer :name
相当于下面的两个方法。
- def name
- @name
- end
- def name=(name)
- @name=name
- end
类变量访问器class variable accessor
- class Demo
- class << self
- attr_accessor :name
- end
- @name="andy"
- end
- puts Demo.name # andy
类变量访问器class variable accessor
- class Demo
- class << self; attr_accessor :name end
- @name="virus"
- end
- puts Demo.name # virus
别名alias
- class Demo
- def longmethod
- end
- alias shortmethod longmethod
- end
- demo=Demo.new
- demo.longmethod
- demo.shortmethod