perseverance perseverance - 2 months ago 6
Ruby Question

When creating a method without a class in the Rails console, what class is the method under?

Say I did the following while in the

rails console
:

def test
puts "hi"
end


I can run
test
and I see hi in the console. What I am trying to understand is where is this
test
method attached to? Is it part of a class? Is there a command I can use to determine where the method belongs to?

Thanks!

Answer

Ruby creates a object of Object class when you run your console, so all methods are private instance methods of Object class, you can run this to verify.

        Object.private_instance_methods.include? :test

So when you define your methods in console It is interpreted to this

class Object
 def test
  puts "hi"
end
end

More explanation

I was wanted to explain this but a detailed article is written on this topic,

https://www.sitepoint.com/rubys-top-self-object/