Wednesday, November 07, 2018

Difference Between IRB and Code in Ruby File

One of the differences is that any method defined at the top level in a Ruby file becomes a private method in Object.

def greet
  p 'hi'
end

o = Object.new
o.greet

NoMethodError: private method ‘greet’ called for #. You can verify this:

 def greet
   p 'hi'
 end 

 p self.private_methods.grep(/greet/)

But in IRB it becomes a public method.

$ irb
2.3.3 :001 > def greet
2.3.3 :002?>   p 'hi'
2.3.3 :003?>   end
 => :greet
2.3.3 :004 > o = Object.new
 => # 
2.3.3 :005 > o.greet
"hi"
 => "hi"
 
Hey, you can also use self to call the greet method like this:

self.greet

or just

greet