Default arguments in Ruby allow developers to specify fallback values for method parameters. This feature enhances code flexibility and reduces the need for multiple method definitions.
To define a method with default arguments, assign a value to the parameter in the method definition:
def greet(name = "World")
puts "Hello, #{name}!"
end
greet # Output: Hello, World!
greet("Ruby") # Output: Hello, Ruby!
In this example, "World" is the default value for the name
parameter. If no argument is provided when calling the method, it uses the default value.
Ruby methods can have multiple default arguments:
def create_user(name, age = 30, role = "Member")
puts "Created user: #{name}, Age: #{age}, Role: #{role}"
end
create_user("Alice") # Output: Created user: Alice, Age: 30, Role: Member
create_user("Bob", 25) # Output: Created user: Bob, Age: 25, Role: Member
create_user("Charlie", 35, "Admin") # Output: Created user: Charlie, Age: 35, Role: Admin
Default arguments can be combined with keyword arguments for even more flexibility:
def configure(host: "localhost", port: 8080, ssl: false)
puts "Configuring: Host: #{host}, Port: #{port}, SSL: #{ssl}"
end
configure # Uses all defaults
configure(port: 3000) # Overrides only the port
configure(ssl: true, host: "example.com") # Overrides host and ssl
This approach allows callers to specify only the arguments they want to override, making the method highly customizable.
When working with default arguments, keep these points in mind:
By mastering default arguments, you can write more concise and flexible Ruby code, reducing duplication and improving maintainability.