Top-level methods and constants

A couple of questions regarding the top-level environment of execution.

  • The Pickaxe says on page 376 that top-level methods are defined as
    private instance methods of Object, whereas Ruby for Rails says on
    page 203 they are private instance methods of the Kernel module. Which
    one is correct?

  • Which is the actual container of a top-level constant?

– fxn

Hi –

On Sun, 11 Nov 2007, Xavier N. wrote:

A couple of questions regarding the top-level environment of execution.

  • The Pickaxe says on page 376 that top-level methods are defined as private
    instance methods of Object, whereas Ruby for Rails says on page 203 they are
    private instance methods of the Kernel module. Which one is correct?

The Pickaxe is right. I believe it got fixed in later printings of
R4R, though. I can’t remember what led to the original mistake – I
think I misinterpreted some method-list output I was getting while
examining it all in irb, or something.

  • Which is the actual container of a top-level constant?

You may not want me to answer :slight_smile: But I do believe it’s Object.

ruby -ve “A=1; Object::A; Kernel::A”
ruby 1.8.6 (2007-03-13 patchlevel 0) [i686-darwin8.10.1]
-e:1: uninitialized constant Kernel::A (NameError)

(plus a couple of void context warnings which don’t matter)

David

On Nov 10, 2007 12:10 PM, Xavier N. [email protected] wrote:

A couple of questions regarding the top-level environment of execution.

  • The Pickaxe says on page 376 that top-level methods are defined as
    private instance methods of Object, whereas Ruby for Rails says on
    page 203 they are private instance methods of the Kernel module. Which
    one is correct?

Looks like the pickaxe:

def foo
end

self.private_methods.include?(“foo”) # => true
Object.private_instance_methods(false).include?(“foo”) # => true
Kernel.private_instance_methods(false).include?(“foo”) # => false

Note though that in irb top level methods are public:
irb(main):001:0> def foo
irb(main):002:1> end
=> nil
irb(main):003:0>
irb(main):004:0* self.private_methods.include?(“foo”)
=> false
irb(main):005:0> Object.private_instance_methods(false).include?(“foo”)
=> false
irb(main):006:0> Kernel.private_instance_methods(false).include?(“foo”)
=> false
irb(main):007:0> Object.instance_methods(false).include?(“foo”)
=> true
irb(main):008:0>


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/