Perish

博客园 首页 联系 订阅 管理

#### instance_eval从名字上看,它的调用者必须是一个实例:

class A
end
a = A.new
a.instance_eval do 
  self #===>a
  def method1
     puts "it's a's instance method, only for a"
  end
end

a.method1 #=it's a's instance method, only for a

同样,因为类class本身也是Class类的一个实例,instance_eval也可以用在类上,这个时候就可以在其中定义该类的singleton_method,即为该类的类函数.

class A
end
A.instance_eval do
    self # A
    def method1
        puts "it's A's class method"
     end
end

A.method1 # it's A's class method

####  class_eval 的调用者receiver必须是一个,而在class_eval block的内部,self即为receiver类本身.

class A
end

A.class_eval do
  self  # => A
  # current class => A
end

  根据这个定义,如果在一个类上调用了class_eval,就可以在其中定义该类的实例函数 instance_method

class A
end

a = A.new
a.method1
#=> NoMethodError: undefined method `method1' for #<A:0x10043ff70>

A.class_eval do
  self  # => A
  # current class => A
  def method1
    puts 'this is a instance method of class A'
  end
end

a.method1
#=> this is a instance method of class A

  详细讲解:https://ruby-china.org/topics/2442

posted on 2014-09-17 15:13  ---小青年---  阅读(208)  评论(0编辑  收藏  举报