In programming, an argument is a value you pass to a method so it can do something useful with it, like perform a calculation or print a message.
Here's a quick example of Ruby arguments. You can read the rest of the tutorial for more.
Example
def add_numbers(a, b)
sum = a + b
puts "Sum: #{sum}"
end
add_numbers(2, 3)
# Output:
# Sum: 5
Here, the method add_numbers
takes two arguments: 2 and 3. These values are added together, and the result is printed.
Method Argument with Default Values
In Ruby, you can assign default values to method parameters using the =
operator. If a value isn't provided during the call, Ruby uses the default value. For example,
def add_numbers(a = 7, b = 8)
sum = a + b
puts "Sum: #{sum}"
end
# Method call with two arguments
add_numbers(2, 3)
# Method call with one argument
add_numbers(2)
# Method call with no arguments
add_numbers
Output
Sum: 5 Sum: 10 Sum: 15
In the above example, notice the method definition:
def add_numbers(a = 7, b = 8)
...
end
Here, we have provided default values 7 and 8 for parameters a
and b
, respectively. Here's how this program works:
1. add_numbers(2, 3)
Both values are passed during the method call. Hence, these values are used instead of the default values.
2. add_numbers(2)
Only one value is passed during the method call. The value 2 is assigned to parameter a
, and the default value is used for parameter b
.
3. add_numbers()
No value is passed during the method call. Hence, the default value is used for both parameters a
and b
.
Ruby Keyword Arguments
Ruby supports keyword arguments, where each parameter is explicitly named during the method call.
This makes the code easier to read and avoids confusion about argument order. For example,
def display_info(first_name:, last_name:)
puts "First Name: #{first_name}"
puts "Last Name: #{last_name}"
end
display_info(last_name: "Cartman", first_name: "Eric")
Output
First Name: Eric Last Name: Cartman
Here, the method display_info
takes two keyword arguments: first_name
and last_name
.
During the method call, you pass the arguments using their names.
This means the order doesn't matter; Ruby matches the names, not the positions.
Note: If you forget to pass any required keyword arguments when calling a method, Ruby will raise an ArgumentError
. To avoid this, always pass all required keyword arguments.
Arbitrary Arguments
Sometimes, you may not know how many arguments will be passed to a method. In such cases, Ruby allows you to use arbitrary arguments.
You can do this by adding an asterisk (*
) before a parameter name. This collects all extra arguments into an array. For example,
# Program to find the sum of multiple numbers
def find_sum(*numbers)
result = 0
numbers.each { |num| result += num }
puts "Sum = #{result}"
end
# Method call with 3 arguments
find_sum(1, 2, 3)
# Method call with 2 arguments
find_sum(4, 9)
Output
Sum = 6 Sum = 13
In the above example, we have created the method find_sum
that accepts arbitrary arguments. Notice the lines,
find_sum(1, 2, 3)
find_sum(4, 9)
Here, we are able to call the same method with different arguments.
Note: numbers
is treated as an array inside the method, so we can use array methods like .each
to loop through the values.
Arbitrary Keyword Arguments
Ruby also supports arbitrary keyword arguments using the double asterisk (**
) operator. For example,
def print_info(**details)
details.each do |key, value|
puts "#{key}: #{value}"
end
end
print_info(name: "Charlie", age: 30)
Output
name: Charlie age: 30
Here, the method accepts any number of keyword arguments using **details
. Inside the method, the arguments are stored in a hash, which we loop through using .each
.
More on Ruby Arguments
A block argument allows a method to accept a block of code, which can then be executed inside the method. Ruby provides two ways to handle blocks:
1. Using yield
def greet(name)
puts "Hello, #{name}"
yield if block_given?
end
greet("Alice") { puts "Have a great day!" }
Output
Hello, Alice Have a great day!
Here, the block is passed during the method call and executed using yield
. The method checks for a block using block_given?
to avoid errors.
2. Using &block
def greet(name, &block)
puts "Hello, #{name}"
block.call if block
end
greet("Bob") { puts "Welcome!" }
Output
Hello, Bob Welcome!
Here, the block is received as a variable named block and called using block.call
.
To learn more about blocks, visit Ruby blocks.
Ruby allows you to mix various types of arguments in a single method. For example,
def introduce(name, age = 18, city:, country: "Nepal")
puts "Name: #{name}"
puts "Age: #{age}"
puts "City: #{city}"
puts "Country: #{country}"
end
introduce("Ruby", city: "Kathmandu")
Output
Name: Ruby Age: 18 City: Kathmandu Country: Nepal
Ruby enforces a strict order when defining method parameters. You cannot mix them randomly.
The required order is:
- Required positional arguments
- Optional/default positional arguments
- Arbitrary arguments (
*args
) - Required keyword arguments
- Keyword arguments with default values
- Arbitrary keyword arguments (
**kwargs
) - Block arguments (
&block
)
If you mix argument types in the wrong order, Ruby will raise a SyntaxError
. For example,
# Invalid: keyword argument before *args
def wrong_order(name:, *args)
end
Always follow the correct order to define your method arguments safely and clearly.