Defining a Method
Part of the Fundamentals section of Coddy's Ruby journey — lesson 48 of 88.
As your programs grow, you'll find yourself writing the same code over and over. Methods let you bundle code into reusable blocks that you can call by name whenever you need them.
In Ruby, you define a method using the def keyword, followed by the method name, and close it with end:
def greet
puts "Hello there!"
endThis creates a method called greet. The code inside won't run until you call the method. To call it, simply use its name:
greet # Outputs: Hello there!You can call a method as many times as you want. Each call executes all the code inside the method:
def say_goodbye
puts "Goodbye!"
puts "See you soon!"
end
say_goodbye
say_goodbyeThis prints both lines twice. Method names in Ruby follow the same convention as variables: lowercase letters with underscores separating words, like calculate_total or print_message.
Challenge
EasyDefine a method called welcome_message that prints the following two lines when called:
Welcome to Ruby!
Let's start coding!After defining the method, call it twice to display the message two times.
The expected output should be:
Welcome to Ruby!
Let's start coding!
Welcome to Ruby!
Let's start coding!Cheat sheet
Methods let you bundle code into reusable blocks. Define a method using def and close it with end:
def greet
puts "Hello there!"
endCall a method by using its name:
greet # Outputs: Hello there!You can call a method multiple times:
def say_goodbye
puts "Goodbye!"
puts "See you soon!"
end
say_goodbye
say_goodbyeMethod names use lowercase letters with underscores separating words: calculate_total, print_message.
Try it yourself
# TODO: Define the welcome_message method below
# TODO: Call the method twice belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False9Methods
Defining a MethodMethod ParametersReturn ValuesRecap - Sigma MethodRecap - Validation MethodDefault Parameter Values