Project

General

Profile

Actions

Bug #9055

closed

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

Added by concorde (Alexander Korolkov) about 11 years ago. Updated about 11 years ago.

Status:
Rejected
Assignee:
-
Target version:
ruby -v:
ruby 2.1.0dev (2013-10-27 trunk 43439) [x86_64-linux]
[ruby-core:58052]

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

Updated by matz (Yukihiro Matsumoto) about 11 years 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.

Actions

Also available in: Atom PDF

Like0
Like0