Ruby Methods
A method is a named block of code that does one job. A program defines a method once and calls it by name each time the job is needed.
The same lines copied three times
A class greets three people as they arrive. The greeting takes two lines, and the program copies both lines for each person.
puts "Hello and welcome!"
puts "We are glad you are here."
puts "Hello and welcome!"
puts "We are glad you are here."
puts "Hello and welcome!"
puts "We are glad you are here."One definition with def and end
The word def starts the method and the word end closes it. The call after end runs the greeting once.
def greet
puts "Hello and welcome!"
puts "We are glad you are here."
end
greetCalled by name three times
The definition stays in one place. Three calls print the greeting three times.
def greet
puts "Hello and welcome!"
puts "We are glad you are here."
end
greet
greet
greetExample
def greet
puts "Hello and welcome!"
puts "We are glad you are here."
end
def close_doors
puts "Doors close at six."
end
greet
greet
close_doorsKey points
- A method wraps one job in a name.
- Use def to start a method definition.
- Use end to close a method definition.
- A method runs only when its name is called.
- One definition can be called many times.
- Method names use snake_case, like close_doors.
In this example, the program defines two methods. The greet method prints the two greeting lines. The close_doors method prints one line about the doors. Two greet calls print the greeting twice, and one close_doors call prints the last line.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
What does def do in a Ruby program?