Top-level methods private?


#1

I understand that methods defined at the top-level, not in any class,
become methods of the class Object. Pickaxe 2 says in its discussion
of the top-level environment (page 293 in my paper copy) “we’re
actually creating (private) instance methods for class Object”. I
think the “(private)” part is wrong because I can invoke top-level
methods using a receiver, which I shouldn’t be able to do for private
methods.

Here’s an example.

def foo; puts ‘in foo’; end
class Bar; end
bar = Bar.new
bar.foo

Am I misunderstanding this?


#2

Mark V. wrote:

def foo; puts ‘in foo’; end
class Bar; end
bar = Bar.new
bar.foo

Am I misunderstanding this?

Don’t you get an error when you call bar.foo?

$ ruby -e "
def foo; puts ‘in foo’; end
class Bar; end
bar = Bar.new
bar.foo
"
-e:5: private method `foo’ called for #Bar:0xb7dcccec (NoMethodError)


#3

On 6/12/06, Joel VanderWerf removed_email_address@domain.invalid wrote:

$ ruby -e "
def foo; puts ‘in foo’; end
class Bar; end
bar = Bar.new
bar.foo
"
-e:5: private method `foo’ called for #Bar:0xb7dcccec (NoMethodError)

Hmm … yes I do. However, I don’t get an error if I enter the same
code in irb. That’s all I had tried before because I thought it would
be equivalent. I wonder why it’s different there.


#4

On Jun 12, 2006, at 22:22, Joel VanderWerf wrote:

$ ruby -e "
def foo; puts ‘in foo’; end
class Bar; end
bar = Bar.new
bar.foo
"
-e:5: private method `foo’ called for #Bar:0xb7dcccec
(NoMethodError)

Am I right in guessing that Mark is using irb to evaluate this code,
and that Joel is not? irb has some odd hooks in it, in my experience:

ruby -e “def foo; end; puts Object.private_methods.include?(‘foo’)”
true

irb(main):001:0> def foo; end; puts Object.private_methods.include?
(‘foo’)
false

matthew smillie.


#5

Using both 1.8.2 and 1.8.4: no… the method foo is invoked.

./alex

.w( the_mindstorm )p.


#6

Alexandru P. wrote:

Ohhh… indeed I have tried using irb. Weird!

In irb, ‘def foo; end’ apparently creates a public method of the “main”
object:

irb(main):001:0> self
=> main
irb(main):002:0> def foo; puts “FOO”; end
=> nil
irb(main):003:0> self.foo
FOO
=> nil
irb(main):004:0> class << self; puts
(methods-private_methods).grep(/foo/); end
foo
=> nil

So the “top level” of irb differs from the normal top level of ruby.


#7

Ohhh… indeed I have tried using irb. Weird!

./alex

.w( the_mindstorm )p.


#8

Not sure I understand:

irb> sefl
=> main

ruby -e “puts self” => main

why are these different?

./alex

.w( the_mindstorm )p.