0
0
Rubyprogramming~5 mins

Parameters with default values in Ruby

Choose your learning style9 modes available
Introduction
Sometimes, you want a function to work even if some information is missing. Default values let you give a backup answer for those missing pieces.
When you want a method to have optional settings that usually stay the same.
When you want to avoid errors if someone forgets to give all the details.
When you want to make your code simpler by not always asking for every input.
When you want to provide common values but still allow changes if needed.
Syntax
Ruby
def method_name(param1, param2 = default_value2)
  # method body
end
Default values are set using the equals sign (=) after the parameter name.
Parameters with default values should come after parameters without defaults.
Examples
A method that says hello to a name, or to "friend" if no name is given.
Ruby
def greet(name = "friend")
  puts "Hello, #{name}!"
end
Adds two numbers, but if the second number is missing, it uses 10.
Ruby
def add(a, b = 10)
  a + b
end
Orders items with default quantity 1 and price 5.0 if not specified.
Ruby
def order(item, quantity = 1, price = 5.0)
  total = quantity * price
  puts "Order: #{quantity} #{item}(s) for $#{total}"
end
Sample Program
This program shows how the greet method works with and without giving a name.
Ruby
def greet(name = "friend")
  puts "Hello, #{name}!"
end

greet("Alice")
greet
OutputSuccess
Important Notes
If you call a method without a parameter that has a default, Ruby uses the default automatically.
You can mix parameters with and without defaults, but put those with defaults last.
Default values can be any Ruby expression, like numbers, strings, or even method calls.
Summary
Default parameters let methods work even if some inputs are missing.
Use = to set default values after the parameter name.
Put parameters with defaults after those without.