Ruby Parameters
Passing data into methods for flexible functionality
📥 What are Ruby Parameters?
Parameters are variables that receive values when you call a method. They make methods flexible by allowing different inputs each time, enabling code reuse with varying data.
# Method with parameter
def greet(name)
puts "Hello, #{name}!"
end
greet("Alice")
greet("Bob")
Output:
Hello, Alice!
Hello, Bob!
Key Parameter Types
Required
Must be provided when calling
def add(a, b)
a + b
end
Default
Have fallback values
def greet(name = "Friend")
puts "Hi #{name}"
end
Keyword
Named parameters for clarity
def user(name:, age:)
puts "#{name}, #{age}"
end
Splat
Accept multiple arguments
def sum(*numbers)
numbers.sum
end
🔹 Required Parameters
Required parameters must be provided when calling a method. If you forget to pass them, Ruby raises an error. They ensure your method receives all necessary data to function correctly.
# Single parameter
def square(number)
number * number
end
puts square(5)
# Multiple parameters
def introduce(name, age, city)
puts "I'm #{name}, #{age} years old, from #{city}"
end
introduce("Alice", 28, "New York")
# Order matters
def subtract(a, b)
a - b
end
puts subtract(10, 3) # 10 - 3
puts subtract(3, 10) # 3 - 10
Output:
25
I'm Alice, 28 years old, from New York
7
-7
🔹 Default Parameters
Default parameters provide fallback values when arguments aren't passed. This makes methods more flexible and user-friendly, allowing them to work with or without specific inputs while maintaining sensible defaults.
# Single default parameter
def greet(name = "Guest")
puts "Welcome, #{name}!"
end
greet("Sarah")
greet
# Multiple defaults
def create_account(username, role = "user", active = true)
puts "Account: #{username}, Role: #{role}, Active: #{active}"
end
create_account("john123")
create_account("admin456", "admin")
create_account("test789", "tester", false)
# Mix required and default
def calculate_price(amount, tax = 0.1, discount = 0)
total = amount + (amount * tax) - discount
puts "Total: $#{total}"
end
calculate_price(100)
calculate_price(100, 0.15)
calculate_price(100, 0.15, 10)
Output:
Welcome, Sarah!
Welcome, Guest!
Account: john123, Role: user, Active: true
Account: admin456, Role: admin, Active: true
Account: test789, Role: tester, Active: false
Total: $110.0
Total: $115.0
Total: $105.0
🔹 Keyword Parameters
Keyword parameters use names instead of position, making method calls clearer and self-documenting. They prevent errors from argument order and make code more maintainable, especially with many parameters.
# Required keyword parameters
def create_user(name:, email:, age:)
puts "User: #{name}, Email: #{email}, Age: #{age}"
end
create_user(name: "Alice", email: "[email protected]", age: 25)
create_user(age: 30, name: "Bob", email: "[email protected]") # Order doesn't matter
# Optional keyword parameters
def send_email(to:, subject: "No Subject", body: "")
puts "To: #{to}"
puts "Subject: #{subject}"
puts "Body: #{body}"
end
send_email(to: "[email protected]")
send_email(to: "[email protected]", subject: "Hello", body: "Welcome!")
# Mix positional and keyword
def register(username, email:, password:, age: 18)
puts "Username: #{username}, Email: #{email}, Age: #{age}"
end
register("john_doe", email: "[email protected]", password: "secret123")
Output:
User: Alice, Email: [email protected], Age: 25
User: Bob, Email: [email protected], Age: 30
Subject: No Subject
Body:
Subject: Hello
Body: Welcome!
Username: john_doe, Email: [email protected], Age: 18
🔹 Splat Operator (*)
The splat operator collects multiple arguments into an array. It's perfect when you don't know how many arguments will be passed, allowing methods to handle variable numbers of inputs elegantly.
# Variable number of arguments
def sum(*numbers)
total = numbers.sum
puts "Sum of #{numbers.inspect} = #{total}"
end
sum(1, 2, 3)
sum(10, 20, 30, 40, 50)
sum(5)
# Mix regular and splat parameters
def introduce(name, *hobbies)
puts "I'm #{name}"
puts "My hobbies: #{hobbies.join(', ')}"
end
introduce("Alice", "reading", "coding", "gaming")
# Double splat for keyword arguments
def display_info(name, **details)
puts "Name: #{name}"
details.each { |key, value| puts "#{key}: #{value}" }
end
display_info("Bob", age: 30, city: "NYC", job: "Developer")
Output:
Sum of [1, 2, 3] = 6
Sum of [10, 20, 30, 40, 50] = 150
Sum of [5] = 5
I'm Alice
My hobbies: reading, coding, gaming
Name: Bob
age: 30
city: NYC
job: Developer
🔹 Practical Examples
Real-world parameter usage demonstrates how to build flexible, reusable methods. These examples show common patterns for handling user input, calculations, and data processing in everyday Ruby programming tasks.
# Shopping cart calculator
def calculate_total(price, quantity = 1, discount: 0, tax: 0.08)
subtotal = price * quantity
after_discount = subtotal - (subtotal * discount)
total = after_discount + (after_discount * tax)
puts "Total: $#{total.round(2)}"
end
calculate_total(50, 2)
calculate_total(100, 3, discount: 0.1)
calculate_total(75, 1, discount: 0.2, tax: 0.1)
# User profile builder
def build_profile(name, age, *skills, city: "Unknown", active: true)
puts "Profile: #{name}, #{age} years old"
puts "Skills: #{skills.join(', ')}"
puts "City: #{city}, Active: #{active}"
end
build_profile("John", 28, "Ruby", "JavaScript", "Python", city: "Boston")
Output:
Total: $108.0
Total: $291.6
Total: $66.0
Profile: John, 28 years old
Skills: Ruby, JavaScript, Python
City: Boston, Active: true