Global methods under object supposedly unaccessible

documentation:

“By default, all methods in Ruby classes are public - accessible by
anyone. There are, nonetheless, only two exceptions for this rule: the
global methods defined under the Object class, and the initialize
method for any class. Both of them are implicitly private.”

class Object
def something
puts “something”
end
end
=> nil

class XYZ
end
=> nil

xyz = XYZ.new
=> #XYZ:0x10d067580

xyz.something
something

So then why was I able to access something?

  1. Post the definition of private.

  2. Execute this program:

puts ‘hello’

  1. What conclusions do you draw from that?

A private method is internal to the implementation of a class, and it
can only be called by other instance methods of the class (or its
subclasses). Private methods are implicitly invoked on self, and may
not be explicitly invoked on an object. If m is a private method, then
you must ibnvoke it in functional style as m.

But look at this:

1.9.3p0 :032 > class Object
1.9.3p0 :033?> def apple2
1.9.3p0 :034?> puts ‘apple2’
1.9.3p0 :035?> end
1.9.3p0 :036?> end
=> nil
1.9.3p0 :037 > self.apple2
apple2
=> nil

Or this:

1.9.3p0 :038 > def apple2
1.9.3p0 :039?> puts ‘apple2’
1.9.3p0 :040?> end
=> nil
1.9.3p0 :041 > self.apple2
apple2
=> nil

I invoked apple2 on self (an explicit receiver). However, according to
documentation, defining apple2 in Object should have made it private.

Only this would work:

1.9.3p0 :025 > class Object
1.9.3p0 :026?> private
1.9.3p0 :027?> def apple1
1.9.3p0 :028?> puts ‘apple1’
1.9.3p0 :029?> end
1.9.3p0 :030?> end
=> nil
1.9.3p0 :031 > self.apple1
NoMethodError: private method `apple1’ called for main:Object

However, in the above example, I was forced to use the private method.
The documentation says “any global methods declared outside of a class
definition - those methods are defined as private instance methods of
Object.”
In my first examples, I defined a method outside of class definition.
But was still able to invoke it on self (self being Object in that
case).

On Wednesday, October 3, 2012 6:08:31 AM UTC+1, John M. wrote:

This is one of those cases where irb behaves slightly differently to a
‘normal’ ruby script. If you copy that code into a standalone file and
run
that then the call to self.apple2 will raise an exception

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs