Ruby 动态添加对象的方法 ( eigenclass --- 1 )

zputee · 2013年04月24日 · 最后由 zputee 回复于 2013年04月25日 · 3773 次阅读

一、简介 对象的 singleton_class,Matz 也称 eigenclass。 表面上看不到,但它就像影子一样,一直伴随着对象,无处不在,比较神秘吧。

我给它起了别名,对象伴侣类。 类也是对象,类也有对象伴侣类

二、动态向对象添加方法,即对象的单例方法 (对象的 eigenclass 类的实例方法)

class MyClass
end
my_object = MyClass.new

#方法1
class << my_object
  def hello1
    p 'hello,world'
  end
end
#方法2 , send
my_object.singleton_class.send(:define_method, :hello2){'hello, world2 '}

#方法3,通过给类添加了实例方法
my_object.class.send(:define_method, :hello3){'hello, world3 '}

#方法4(等效)
my_object.instance_eval %{
  def hello4
    p 'hello,world4'
  end
}
#方法5(等效,但self 语义有点乱,不提倡本方法)
my_object.instance_eval %{
  def self.hello5
    p 'hello,world5'
  end
}
#写法6   ---  2013.4.25 
def my_object.hello6
    p 'hello,world6'
end
#写法7  ---  2012.4.25
module M
  def hello7
    p 'hello world7'
  end
end
class <<my_object
  include M
end  

my_object.hello   #=>"hello,world"
my_object.hello2 #=>"hello,world2"
my_object.hello3 #=>"hello,world3"
my_object.hello4 #=>"hello,world4"
my_object.hello5 #=>"hello,world5"
my_object.hello6 #=>"hello,world6"
my_object.hello7 #=>"hello,world7"

my_object.singleton_methods
my_object.singleton_class.instance_methods(false)

my_object.class.instance_methods(false)

总结:

  1. 向对象的 singleton_class 类添加(对象单例方法)
  2. 向对象的类添加(所有实例都可调用)

  3. my_object 是 my_object.singleton_class 的实例,现有蛋还是现有鸡,有点乱?

  4. X + y = my_object.methods = my_object.singleton_class.instance_methods 其中: X=my_object.instance_methods Y=my_object.singleton_methods = my_object.singleton_class.instance_methods(false)


三、向对象的 eigenclass 添加方法(理论上可行,不常用)

class <<my_object
  def self.hi
    p 'hi,world'
  end
end
my_object.singleton_class.hi  #=>"hi, world"
my_object.singleton_class.methods

@zputee 看了你这两天发的帖子,真心喜欢,完全可以直接转到 Wiki 上去了,对于这些帖子,我只有一句话想说:楼主你上传个头像吧!

#1 楼 @lgn21st谢谢,本人也刚开始认真学,请多指教。gravatar 上不了呀

#2 楼 @zputee 刚开始学就这么认真;) 👍

#3 楼 @skandhas 很早就接触 ruby,一直没有认真 😔

需要 登录 后方可回复, 如果你还没有账号请 注册新账号