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.
def method_name(param1, param2 = default_value2) # method body end
def greet(name = "friend") puts "Hello, #{name}!" end
def add(a, b = 10) a + b end
def order(item, quantity = 1, price = 5.0) total = quantity * price puts "Order: #{quantity} #{item}(s) for $#{total}" end
def greet(name = "friend") puts "Hello, #{name}!" end greet("Alice") greet
def greet(name = "Guest")def greet(name = "Guest"), if no name is passed, "Guest" is used.= value after the parameter name.b = 5 correctly. def add(a =, b 5); a + b; end has invalid syntax. def add(a, b: 5); a + b; end uses keyword argument style, not default parameter. def add(a, b); b = 5; a + b; end assigns inside method body, not default parameter.def multiply(x, y = 2) x * y end puts multiply(4) puts multiply(4, 3)
multiply(4) uses default y=2, so 4*2=8. Second call: multiply(4,3) uses y=3, so 4*3=12.def greet(name = "Guest", age)
"Hello #{name}, you are #{age} years old."
endname has default, but age does not and comes after. This causes syntax error.order that takes a product name and an optional quantity with default 1. Which is the best way to define it to allow calling order("apple") and order("apple", 5)?product first and quantity with default 1 second. def order(product = "apple", quantity); "Order #{quantity} #{product}(s)"; end has default before required, invalid. def order(quantity = 1, product); "Order #{quantity} #{product}(s)"; end swaps order incorrectly. def order(product, quantity); quantity ||= 1; "Order #{quantity} #{product}(s)"; end assigns default inside method but requires both arguments.Pass the test and this pattern moves unknown