Bug #6838

class_eval and instance_eval do not scope class names the same as direct code

Added by Chris Poirier over 1 year ago. Updated over 1 year ago.

[ruby-core:47013]
Status:Rejected
Priority:Normal
Assignee:-
Category:-
Target version:-
ruby -v:ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11] Backport:

Description

class X
def self.f()
puts "::X"
end
end

class Y
class X
def self.f()
puts "Y::X"
end
end

def self.c()
X.f()
end
end

Y.class_eval do
def self.k()
X.f()
end
end

Y.c
Y.class_eval { X.f() }
Y.k

Y.c outputs "Y::X"
Y.class_eval { X.f() } outputs "::X"
Y.k also outputs "::X"

Similar behaviour happens with instance_eval:

class X
def f()
puts "::X"
end
end

class Y
class X
def f()
puts "Y::X"
end
end

def c()
X.new.f()
end
end

Y.new.c
Y.new.instance_eval { X.new.f() }

My expectation is that classeval and instanceeval should map class names the same as code written directly in the class, as they do with function names.

History

#1 Updated by Chris Poirier over 1 year ago

On more thought, I can understand that Ruby views class names the same way it does variables, and so pulls them from the binding. It just doesn't feel like it's the right behaviour, in this context.

#2 Updated by Shugo Maeda over 1 year ago

  • Status changed from Open to Rejected

cpoirier (Chris Poirier) wrote:

My expectation is that classeval and instanceeval should map class names the same as code written directly in the class, as they do with function names.

The current behavior is intended.
From the documentation of Module#class_eval:

Evaluates the string or block in the context of _mod_, except that when
a block is given, constant/class variable lookup is not affected.

This is because constants are searched statically rather than dynamically in Ruby.

#3 Updated by Alexey Muranov over 1 year ago

I think constants are searched "half-dynamically", as, for example, inheritance hierarchy is searched, but only after the visual "indented" hierarchy. Is #6810 related?

Also available in: Atom PDF