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:
Syntax
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
def greet(name, greeting = "Hello")
puts "#{greeting}, #{name}!"
end
greet("Alice")
greet("Bob", "Welcome")
Login to try C/C++/Java/PHP code in the editor
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
- Putting a default parameter before a required one, which makes calls confusing.
- Passing
niland expecting the default to be used, whennilis a real value and replaces the default. - Calling
greet(nil)and expecting the default greeting, when passingnilexplicitly 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: