Forum: Ruby Instance_eval and constants lookup rules in ruby 1.9

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
33def21bd696e6c290c9f5fba47930c8?d=identicon&s=25 Daniel Mendler (Guest)
on 2009-04-15 18:15
(Received via mailing list)
Hi,

what happend to the constant lookup rules in ruby 1.9? It seems
constants in blocks that are evaluated with instance_eval are looked up
only in the evaluating class but not in the scope the block was defined.

This works in Ruby 1.8 but not in 1.9:
======================================

class X
  def run(&block)
    instance_eval(&block)
  end
end

module A
  I_AM_NOT_FOUND = 666
  a = X.new
  a.run {
    puts I_AM_NOT_FOUND
  }
end

Ruby 1.8 finds the constants only if they are in the scope where the
block is defined. Why was this behaviour changed?

Daniel
797ef431a5e1295b56c08e1db4c8d2df?d=identicon&s=25 botp (Guest)
on 2009-04-16 05:58
(Received via mailing list)
On Thu, Apr 16, 2009 at 12:13 AM, Daniel Mendler
<dmendler@wurzelteiler.de> wrote:

i should expect that behaviour if using *instance*_eval inside
*modules*.

i have many options though (note test2.rb does not use instance_eval)...


botp@jedi-hopeful:~$ cat test?.rb

#--test1.rb------------
class X
 def run(&block)
   instance_eval(&block)
 end
end
module A
 I_AM_FOUND = 666
 a = X.new
 a.run {
   puts A::I_AM_FOUND
 }
end



#-- test2.rb ---------
class X
 def run(&block)
   block.call
 end
end
module A
 I_AM_FOUND = 666
 a = X.new
 a.run {
   puts I_AM_FOUND
 }
end



#-- test3.rb -----------
class X
  I_AM_FOUND = 666
  def run(&block)
    instance_eval(&block)
  end
end
module A
 a = X.new
 a.run {
   puts I_AM_FOUND
 }
end



#-- test4.rb -----------
class X
 def run(&block)
   instance_eval(&block)
 end
end
I_AM_FOUND = 666
a = X.new
a.run {
  puts I_AM_FOUND
}

botp@jedi-hopeful:~$


kind regards -botp
This topic is locked and can not be replied to.