Menu
Coddy logo textTech

Default Parameter Values

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

Sometimes you want a method to have a sensible fallback when an argument isn't provided. Default parameter values let you define what a parameter should be if the caller doesn't specify it.

To set a default value, use the = sign after the parameter name:

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

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

When you call greet without an argument, Ruby uses "friend" as the default. When you provide an argument, it overrides the default.

You can mix regular parameters with default ones, but parameters with defaults must come after those without:

def power(base, exponent = 2)
  base ** exponent
end

puts power(5)     # Outputs: 25 (5 squared)
puts power(2, 3)  # Outputs: 8 (2 cubed)

This makes methods more flexible. Callers can provide only the essential information while optional details fall back to reasonable defaults.

challenge icon

Challenge

Easy

Define a method called multiply that takes two parameters: a and b. The parameter b should have a default value of 1. The method should return the product of a and b.

Read two integers from input:

  1. The first number (will always be provided)
  2. The second number (may or may not be provided)

If only one input is provided, call the method with just that argument (using the default value for b). If two inputs are provided, call the method with both arguments.

Print the result of the method call.

The input format will be:

  • First line: the first number
  • Second line: either a number or the word none

For example, if the inputs are 7 and 3:

21

If the inputs are 5 and none:

5

If the inputs are 12 and 4:

48

Cheat sheet

Default parameter values provide fallback values when arguments aren't provided. Use the = sign after the parameter name to set a default:

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

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

Parameters with defaults must come after parameters without defaults:

def power(base, exponent = 2)
  base ** exponent
end

puts power(5)     # Outputs: 25 (5 squared)
puts power(2, 3)  # Outputs: 8 (2 cubed)

Try it yourself

# Read input
a = gets.chomp.to_i
b_input = gets.chomp

# TODO: Define the multiply method with parameter b having a default value of 1


# TODO: Call the method appropriately based on whether b_input is "none" or a number
# If b_input is "none", call multiply with only a
# If b_input is a number, call multiply with both a and b

# Print the result
puts result
quiz iconTest yourself

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

All lessons in Fundamentals