Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

To which object are user defined method assigned in Ruby?

In Ruby every method is assigned to an object (right?). Ruby provides a lot of "built in" methods and gives the ability to the user to create "user defined" methods.

Built in methods are all defined in a class like String, Integer, Array and so on. Built in methods are all invoked placing a dot after an object followed by the method call.

string = "example"
string = string.reverse

However, when I define a method with the syntax

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def method_name (args)
   #body
end

to which object is this method assigned? And why when I have to call a method that I have defined I don’t use the "dot syntax" but I just write its name and pass it some arguments without applying it to an object, like this:

method_name args

>Solution :

There is top-level object in Ruby — main

def method_name(args)
  # body
end
self
# => main

self.methods.grep(/method_name/)
# => [:method_name]

main is an instance of Object. Any methods defined in main become instance methods of Object. This makes them available everywhere, meaning that we can call the method without a receiver

Read more

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading