English 中文(简体)
Ruby s def and instance_eval vs_eval
原标题:Ruby s def and instance_eval vs. class_eval

I m宣读了Programing Duncan 1.9的Metaprogramming section of 和I m,在stat_eval /_exec vsinstance_eval//_instance_exec 之间对的内分>。

首先,我的理解是<代码>f。 在<代码>本身的方法表中添加一个方法。 (类别物体):

class A
  puts self  # => A
  def foo; 42; end  # added to the method table of self, so becomes an instance method
end
A.new.foo  # => 42

如果我们使用<条码>等值_eval,我们就采取同样的行动:

A.class_eval do
  puts self  # => A
  def bar; 42; end  # same as above
end
A.new.bar  # => 42

但是,<代码>instance_eval中的一些内容。 情况不同:

A.instance_eval do
  puts self  # => A
  def baz; 42; end  # added to the method table of an anonymous
                    # singleton class of self, so becomes a class method
end
puts A.baz  # => 42

s =  string 
s.instance_eval do ... end  # same behavior, so now def creates an instance method

因此,我理解<代码>_eval和instance_eval之间的功能差异。

但<代码>_eval和_instance_eval各栏目中的情形见exactly 具体来说,<代码>本身指明了同一物体, local_variables也一样。 因此,在制作<条码>f的区块内发生的情况如何不同?

我是否可以阅读一些文件? The RDoc for instance_eval 无帮助。 看看来文方,instance_eval 似乎设立了单一州级物体,而_eval。 否——但这种区别在《刑法》之外在鲁比拉一级是否明显?

最佳回答
问题回答

仅增加@krusty。 ar s response:def and define_method Add methods to the present method definition context (我认为,它所说的话,我并不肯定,不是现在的<代码>自封/代码”。)

这只是单元、班级或单顿级体内的情况,这两者的情况相同。

但是,例如,在文字体(最高层)中,<代码>自行main物体,但现行方法定义背景为。 目标





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...