How to understand the difference between class_eval() and instance_eval()?

前端 未结 5 1843
终归单人心
终归单人心 2020-12-02 04:47
Foo = Class.new
Foo.class_eval do
  def class_bar
    \"class_bar\"
  end
end
Foo.instance_eval do
  def instance_bar
    \"instance_bar\"
  end
end
Foo.class_bar            


        
5条回答
  •  孤城傲影
    2020-12-02 05:07

    I think you got it wrong. class_eval adds the method in the class, so all instances will have the method. instance_eval will add the method just to one specific object.

    foo = Foo.new
    foo.instance_eval do
      def instance_bar
        "instance_bar"
      end
    end
    
    foo.instance_bar      #=> "instance_bar"
    baz = Foo.new
    baz.instance_bar      #=> undefined method
    

提交回复
热议问题