Welcome to day 17 of the 49 Days of Ruby! 🎉
Today we are looking at an area that we have touched upon quite a lot in the past 16 days, but we have never focused on. The method is a cornerstone of programming in Ruby, and for day 17 we will devote our time to it.
The best way to understand a method is with an example of what it can do for us. Let's take a look:
In the above example, we are making our daily coffee with three different expressions:
If I want to do this as it is, then I need to call each expression separately each day. Wouldn't it be nice if it was all wrapped up together? Hence, the method!
# => coffee
We used a method to combine the expressions together and produce a single result, which is our coffee.
That is the benefit, at its most fundamental level, of a method. It lets you make a set of expressions for a common goal.
Methods can also call other methods! For our
make_coffee method I invoked three other (imaginary) methods. You can see methods as the building blocks of an application.
Each method should encapsulate the smallest amount of logic possible. This is because it makes it much simpler, later on, to edit it and trace back bugs, and also, you can build tests easier for smaller chunks of code than for more convoluted methods.
Why don't you open up a session of IRB on your machine and play around with method creation today! Share your learnings with the community after with the hashtag #49daysofruby.
Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.