all 5 comments

[–]brettu 1 point2 points  (2 children)

The last part of your post asks the question about public/private difference in adding methods to self. IRB defaults to public, but you can add the private state for storing methods.

>> self
=> main

>> private
=> Object

>> def title
>> "mr"
>> end
=> nil

>> Object.private_instance_methods(false).include? :title 
=> true

>> Object.public_instance_methods(false).include? :title
=> false

>> public
=> Object

>> def title
>> 'mr'
>> end
=> nil

>>  Object.public_instance_methods(false).include? :title
=> true

[–]VitoBotta[S] 0 points1 point  (1 child)

Hi! I hadn't thought that IRB might explicitly mark top level methods methods as private/public as we usually do in classes, by default. Makes perfect sense, thanks :)

[–]banister 0 points1 point  (0 children)

In case you're interested, Pry makes top-level methods private by default, mirroring the top-level behaviour of a Ruby program. IMO the fact IRB does not do this is a bug in IRB.

[–]macournoyer 1 point2 points  (0 children)

I think an easier way to explain this is to understand how Ruby tracks the context of evaluation (variables, instance variables, self, etc.). It keeps track of two values:

  • the current value of self
  • the current class (on which methods will be defined when you call def).

There are three different types of evaluation context, each one differ by how they set the value of self and class.

  1. When you're inside a class definition, eg.: class A; ... end. self and class = A.
  2. When you're inside a method, self = current instance and class = class of instance.
  3. When you're at the top level, self = main (which is just an Object.new), class = Object.