DEV Community

Cover image for Ruby Methods Broken Down

Posted on • Updated on

Ruby Methods Broken Down

Ruby methods are actions and instructions for Ruby objects that are wrapped in def...end keywords. They can be repeatable actions so you don't have to code the same bit over and over, you can apply the method to the class or the instance instead and keep your code friendly and DRY (Don’t Repeat Yourself)!

So what is a class? And what is an instance? Say you have a Vehicle. The vehicle would be the class and the methods would be the parts that define a vehicle: the wheels, steering, fuel, frame. A bicycle can be created by that class so it would be an instance of a vehicle. And since everything in Ruby is an object you can call methods on both the class object and you can call methods on the instance object.

While the syntax is similar, both begin with def and end with...end, they are not interchangeable. Class methods only work when they're called on Classes and instance methods are only good for instances of a class. Mix this up and you'll get slapped with a NoMethodError.

Class methods are recognizable because they're called on the class itself and are denoted with a "." in the method (eg: self.method). They define a function to the class itself and any object generated from that class.

Instances themselves are generated by the class and their instance methods define a function to one instance, or object, of a class.

Ideally, each method deals with one task, so what do you do when you have something more complex to achieve? In comes the helper method. These methods help other methods do their job by taking on a smaller task that is accessible and can be called on in other methods.

Between Class Methods, Instance Methods, and Helper Methods you can code complex problems in Ruby that are easy to understand and free of repetition!


Top comments (2)

sturpin profile image
Sergio Turpín

Awesome Alex!!
Very well explained. Keep it up! ;)

beendra profile image

Thank you!