Menu
Coddy logo textTech

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!"
end

This 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_goodbye

This 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 icon

Challenge

Easy

Define 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!"
end

Call 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_goodbye

Method 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 below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals