Different behavior when running a script against an IRB console?

I have a simple piece of code that defines a method (on a Ruby 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 the Ruby console. I get:

 main Object true 

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

 main Object false 

I cannot understand why I see this behavior. The method is defined in the script, since I can call the method.

I run both on Ruby 2.3.4

+11
source share
1 answer

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

You can find here a link to the main Ruby top-level context.

0
source

Source: https://habr.com/ru/post/1275783/


All Articles