What is a Ruby method?
A method is one, or multiple, lines of Ruby code grouped together with a specific goal.
The goal can be to:
size method on an
Array object gives you a count of elements (information).
pop method removes the last element from the array (change).
When you understand the relationship between objects, classes & methods everything starts to make sense.
Let’s keep learning!
Ruby has many powerful built-in methods you can use, but you can also create your own.
You can define your own Ruby method using the
Here’s the syntax:
def gimme_bacon puts "Bacon plz." end
What’s going on here?
defis part of Ruby’s syntax, it says that we want to
define a method
gimme_baconis the name of the method
puts "Bacon plz."is the body of the method
endmarks the end of the method definition
Defining a method only tells Ruby that you want to create it.
If you want to use it then you need to call the method.
In Ruby, when we use a method, we say that we’re calling it.
You’ll often hear “method call”, or if you’re working with someone who’s an Object-Oriented purist, you may hear that “you’re sending a message”.
Let’s see an example of using a method.
Here you go:
You can call methods on objects.
n = [1,2,3] n.size # 3
n.size is calling the method
size on the object
n, which happens to be an
We get the array’s size.
That depends on the class of the object you’re calling the method on.
An array is going to have different methods than a hash.
You can check the Ruby documentation to find a list of methods for a given class.
One key concept in Ruby is that ALL methods return a value.
Let me explain!
As a result of calling a method, you get something back.
This “something” that you get comes from the last expression in your method definition.
Here’s what I mean:
def number_one 1 end number_one # 1
def add(x,y) x + y end add(5, 6) # 11
We call this “implicit return”, just a fancy name for “automatically return the last thing”.
You can tell Ruby to
return something with a keyword.
def two return 2 end # 2
Notice that your method stops running when you use
You use this is for an early return in your code, or to exit a loop.
You may find some strange Ruby methods.
With names like:
ALL of these are valid method names.
What does the question mark, the exclamation mark, or the equals sign mean?
They are conventions in the Ruby community.
None of these conventions are enforced by the language.
If you follow them, you’ll be able to write more Ruby-like code!
You’ve learned about the power of Ruby methods, how to define them, use them & how to follow proper conventions.
Now it’s your turn to put this into practice 🙂
Thanks for reading!