Bug #9055

Global methods called from an object can access object's internals

Added by Alexander Korolkov 6 months ago. Updated 6 months ago.

[ruby-core:58052]
Status:Rejected
Priority:Normal
Assignee:-
Category:-
Target version:2.1.0
ruby -v:ruby 2.1.0dev (2013-10-27 trunk 43439) [x86_64-linux] Backport:1.9.3: UNKNOWN, 2.0.0: UNKNOWN

Description

=begin
When I run the following program:

def foo()
bar(1)
puts "baz: #{@baz}"
end

def bar(n)
puts "global bar: #{n}"
end

class X
def initialize()
@baz = 42
foo()
end
def bar(n)
puts "X::bar: #{n}"
end
end

foo()
X.new()

I expect that foo() will be called once directly and once indirectly from X constructor. So I expect the following output:

global bar: 1
baz:
global bar: 1
baz:

But in reality I get the following output:

global bar: 1
baz:
X::bar: 1
baz: 42

So when the method foo() is called from a method of object, it runs in the context of this object! It can access instance variables (@baz) and calls object's method bar() instead of global method bar().

What is this, a bug or a hidden feature? It's never mentioned in ruby tutorials or documentation. This behavior is counter-intuitive and may be potentially dangerous.

The same happens in latest ruby-trunk, ruby-1.8 and ruby-1.9.
=end

History

#1 Updated by Yukihiro Matsumoto 6 months ago

  • Status changed from Open to Rejected

That's what global methods are. If you have objection, you need to be more specific and concrete.
What exactly do you want, and what behavior of global methods will satisfy you?

Matz.

Also available in: Atom PDF