Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behaviour when running script vs IRB console?

Tags:

ruby

I have a simple code snippet that defines a method (on Ruby's Main Object), and then checks to see if it is defined.

puts "#{self} #{self.class}"
def foo;end
puts self.methods.include?(:foo)

When I run this in a Ruby console. I get:

main Object
true

If I paste this code into a .rb file and run the file like so ruby test_script.rb, I get the following output

main Object
false

I can't work out why I am seeing this behaviour. The method is being defined in the script, as I can call the method.

I'm running both on Ruby 2.3.4

like image 523
Katy Jones Avatar asked Mar 08 '18 11:03

Katy Jones


1 Answers

IRB binds methods in the top level scope to main as public methods for convienience, but regular Ruby programs bind methods defined in the top level scope to main as private methods.

You can find the reference here Ruby main top level context

like image 138
Shikhir Aggarwal Avatar answered Nov 16 '22 11:11

Shikhir Aggarwal