Method arguments in Ruby allow you to pass data into methods, making them more flexible and reusable. They are essential for creating dynamic and versatile Ruby programs.
In Ruby, method arguments are defined within parentheses after the method name:
def greet(name)
puts "Hello, #{name}!"
end
greet("Alice") # Output: Hello, Alice!
These are mandatory arguments that must be provided when calling the method:
def multiply(a, b)
a * b
end
result = multiply(5, 3) # Returns 15
Ruby allows you to specify default arguments, making them optional:
def power(base, exponent = 2)
base ** exponent
end
puts power(3) # Output: 9 (3^2)
puts power(3, 3) # Output: 27 (3^3)
Keyword arguments allow you to pass arguments by name, improving readability:
def create_user(name:, age:, email:)
puts "Created user: #{name}, #{age} years old, email: #{email}"
end
create_user(name: "Bob", age: 30, email: "bob@example.com")
Ruby supports variable arguments using the splat operator (*):
def sum(*numbers)
numbers.reduce(0, :+)
end
puts sum(1, 2, 3, 4) # Output: 10
When combining different types of arguments, follow this order:
def complex_method(required, optional = "default", *var_args, keyword: "value")
# Method body
end
Understanding Ruby method arguments is crucial for writing flexible and maintainable code. They allow you to create versatile methods that can handle various inputs and scenarios.