ruby 中的类方法和实例方法

来源:互联网 发布:杭州淘宝拍摄基地 收费 编辑:程序博客网 时间:2024/06/04 17:58

类方法与实例方法

实例方法是最常用的方法。假设有一个对象(实例),那么以这个对象为接收者的方法就被称为实例方法

# 实例方法例子p "10, 20, 30, 40".split(",")# "10, 20, 30, 40” 为 String 类的实例, split 为 String 类的实例对象的实例方法 p [1, 2, 3, 4].index(2)#  [1, 2, 3, 4] 为 Array 类的实例, index 为 Array 类的实例对象的实例方法Time.now.to_s => "2013-03-18 03:17:02 +900"# Time.now 为 Time 类的实例, to_s 为 Time 类的实例对象的实例方法 (to_s方法名属于多个对象时为多态 )# 对象(Object)obj = Object.new # 字符串(String) str = "Ruby"# 数值(Float)num = Math::PI  p obj.to_s  #=> "#<Object:0x07fa1d6bd1008>"p str.to_s  #=> "Ruby"p num.to_s  #=> "3.141592653589793"

接收者不是对象而是类本身时的方法,我们称之为类方法

  • 类方法的写法:
    • 类名 . 方法名 Array.new
    • 类名 :: 方法名 Array::new
# 类方法例子Array.new  # 创建新的数组, new 方法为Array类的方法,称为类方法File.rename(oldname, newname) # rename方法 为 File类的方法,称为类方法。class HelloWorld  # hello 方法为类方法  def self.hello(name)    puts "#{name} said hello."   endend
原创粉丝点击