Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 26 / 68

Default Parameter Values

In this lesson you will learn how to give a Ruby parameter a default value so callers can leave it out. This is for anyone searching for "Ruby default parameter how to use".

Writing = value on a parameter sets a default that is used automatically when the caller omits that argument. Picture an order form where leaving a field blank gets you the usual house set.

The sample code defines def greet(name = "Guest"), so greet("Alice") uses the value passed while greet falls back to the default "Guest".

A common stumbling block for beginners is that Ruby lets you omit the parentheses on a method call. greet alone calls the method, but until you are used to that shorthand it can be hard to tell a variable from a method call.

Letting callers omit arguments gives you a flexible method that serves both the simple case and the finely tuned one. In practice it is a favourite technique for methods with optional settings.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)