栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Ruby开发

ruby 中的类方法和实例方法

Ruby开发 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ruby 中的类方法和实例方法

类方法与实例方法

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

# 实例方法例子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  #=> "#"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



作者:0x009
链接:https://www.jianshu.com/p/fc659baa9f9b

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/226420.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号