设为首页收藏本站

嘻皮客娱乐学习网

 找回密码
 中文注册
搜索
打印 上一主题 下一主题
开启左侧

[面试题库] 解释一下ruby中的特殊方法与特殊类

[复制链接]
跳转到指定楼层
楼主
发表于 2014-11-30 20:36:44 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
特殊方法是指某实例所特有的方法。一个对象有哪些行为由对向所属的类决定,但是有时候,一些特殊的对象有何其他对象不一样的行为,在多数程序设计语言中,例如C++和Java,我们必须定义一个新类,但在Ruby中,我们可以定义只从属于某个特定对象的方法,这种方法我们成为特殊方法(Singleton Method)。

class SingletonTest
  def info
   puts “This is This is SingletonTest method”
  end
end

obj1 = SingletonTest.new
obj2 = SingletonTest.new

def obj2.info
  puts “This is obj2″
end

obj1.info
obj2.info

执行结果为:
This is This is SingletonTest method
This is obj2

有时候,我们需要给一个对象定义一系列的特殊方法,如果按照前面的方法,那么只能一个一个定义:

def obj2.singleton_method1
end

def obj2.singleton_method2
end

def obj2.singleton_method3
end
……
def obj2.singleton_methodn
end

这样做非常繁复麻烦,而且无法给出一个统一的概念模型,因此Ruby提供了另外一种方法,
class
回复

使用道具 举报

小黑屋|手机版|嘻皮客网 ( 京ICP备10218169号|京公网安备11010802013797  

GMT+8, 2024-5-15 06:19 , Processed in 0.174008 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表