← Back to Ruby Course | Chapter 7: Methods | Lesson 3 of 7

Default Parameters

A default parameter is a backup answer the method uses when you do not give one, like a sandwich that comes with butter unless you refuse. It lets you leave some inputs out.

In this page:

  1. Default Parameters
Syntax
ruby
def method_name(param1, param2 = default_value)
  # body
end

Default Parameters

A parameter can have a default value, def greet(name, greeting = "Hello"), making it optional at the call site. Default values can reference earlier parameters in the same list.

Parameters with defaults are conventionally placed after required parameters, though Ruby's syntax is flexible about ordering in some cases.

Note: A default value can reference an earlier parameter, like def area(w, h = w) for a default square.

Example: Default Parameters

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

greet("Alice")
greet("Bob", "Welcome")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Putting a default parameter before a required one, which makes calls confusing.
  2. Passing nil and expecting the default to be used, when nil is a real value and replaces the default.
  3. Calling greet(nil) and expecting the default greeting, when passing nil explicitly is a real value and the default "Hello" is not used.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.