Methods are used to don't repeat the same thing all along the program.
Creating Methods
To create a method use this syntax:
def my_first_method
"Hello"
end
puts my_first_method #=> "Hello"
Parameters and Arguments
Parameters are placeholder variables in the template of your method, whereas arguments are the actual variables that get passed to the method when it is called.
def add_ten(number)
number + 10
end
puts add_ten(20) #=> "30"
In this example, number
is a parameter and 20
is an argument.
Default Parameters
If you don't want to always give parameters when calling a method, use default parameters:
def add_ten(number = 1)
number + 10
end
puts add_ten(20) #=> "30"
puts add_ten #=> "11"
What Methods Return
Ruby offers implicit return for methods, it always returns the last expression that was evaluated.
And Ruby offers explicit return too, it is useful to write methods that check for input errors before continuing.
def even_odd(number)
unless number.is_a? Numeric
return "A number was not entered."
end
if number % 2 == 0
"That is an even number."
else
"That is an odd number."
end
end
puts even_odd(30) #=> That is an even number.
puts even_odd("Egg") #=> A number was not entered.
Predicate Methods
Methods that have a question mark (?
) at the end of their name, such as even?
, odd?
, or between?
are predicate methods, which is a naming convention that Ruby uses for methods that return a Boolean.
puts 3.even? #=> false
puts 10.even? #=> true
puts 171.odd? #=> true
puts 13.between?(10, 15) #=> true
Bang Methods
Methods that are denoted with an exclamation mark (!
) at the end of the method name.
By adding a !
to the end of your method, you indicate that this method performs its action and simultaneously overwrites the value of the original object with the result.
whisper = "HEY"
puts whisper.downcase! #=> "hey"
puts whisper #=> "hey"
Top comments (36)
Very helpful @harkato I'm learning Rails right now with little experience with Ruby. This article just tells me how easy and beautiful Ruby programming is.
Btw, Do you work as a Ruby dev or Rails dev?
I started studying ruby last week, my goal is to write articles while I learn this language. I still don't work.
Very nice, cousin!
Great job!
Awesome article!
Good job, man!
Awesome! Keep it up with the great content.
Great articule.. I was looking for something like this.. thx!!
Awesome!
nice article cousin
I dont know anything about ruby, I will follow your articles
I will try my best to keep updating!