Menu
Coddy logo textTech

Method Parameters

Part of the Fundamentals section of Coddy's Ruby journey — lesson 49 of 88.

Methods become much more powerful when they can accept input. Parameters let you pass data into a method, making it flexible and reusable for different situations.

To add parameters, place them inside parentheses after the method name:

def greet(name)
  puts "Hello, #{name}!"
end

greet("Alice")  # Outputs: Hello, Alice!
greet("Bob")    # Outputs: Hello, Bob!

The parameter name acts like a variable inside the method. When you call greet("Alice"), the value "Alice" is assigned to name for that call.

Methods can accept multiple parameters, separated by commas:

def add(a, b)
  puts a + b
end

add(5, 3)   # Outputs: 8
add(10, 7)  # Outputs: 17

The order matters. The first argument goes to the first parameter, the second argument to the second parameter, and so on. You must provide exactly the number of arguments the method expects, or Ruby will raise an error.

challenge icon

Challenge

Easy

Define a method called introduce that takes two parameters: name and age. The method should print a message in the following format:

My name is [name] and I am [age] years old.

Read two inputs:

  1. A string representing the name
  2. An integer representing the age

After defining the method, call it with the input values.

For example, if the inputs are Alice and 25, the output should be:

My name is Alice and I am 25 years old.

If the inputs are Bob and 30, the output should be:

My name is Bob and I am 30 years old.

Cheat sheet

Methods can accept parameters to make them flexible and reusable. Parameters are placed inside parentheses after the method name:

def greet(name)
  puts "Hello, #{name}!"
end

greet("Alice")  # Outputs: Hello, Alice!

The parameter acts like a variable inside the method. When calling the method, the argument value is assigned to the parameter.

Methods can accept multiple parameters, separated by commas:

def add(a, b)
  puts a + b
end

add(5, 3)   # Outputs: 8

The order of arguments matters - the first argument goes to the first parameter, the second to the second parameter, and so on. You must provide exactly the number of arguments the method expects.

Try it yourself

# Read input
name = gets.chomp
age = gets.chomp.to_i

# TODO: Define the introduce method below


# Call the method with the input values
introduce(name, age)
quiz iconTest yourself

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

All lessons in Fundamentals