Ruby的class_eval和instance_eval

阅读更多
class Blog

  def one

     p "method one"

  end

  def self.two

    p "method two"

  end

private

  def three

    p "method three"

  end

end

1、

blog = Blog.new

blog.one #=> ""method one"

2、

Blog.two  #=> "method two"

3、

blog = Blog.new

blog.instance_eval do

  three

end

#=> "method three"

4、

Blog.class_eval do

  def four

      p "method four"

  end

end

blog = Blog.new

blog.four #=> "method four"

5、

Blog.instance_eval do

  def five

      p "method five"

  end

end

Blog.five #=> "method five"

6、

blog = Blog.new

blog.instance_eval do

  def six

      p "method six"

  end

end

blog.six #=> "method six"

你可能感兴趣的:(ruby)