This tutorial will guide you through the fundamentals of defining and calling methods in Ruby. You’ll learn how to use parameters, optional arguments, and return values effectively, with practical examples and engaging exercises to solidify your understanding.
Step 1: Step 1: Defining and Calling Basic Methods
In Ruby, methods are defined using the def keyword followed by the method name and an optional list of parameters. The method body contains the code to be executed, and the method ends with the end keyword. To call a method, simply use its name followed by parentheses.
def greet
puts 'Hello, World!'
end
greet # Output: Hello, World!Practice Exercise
Define a method called say_hello that prints 'Hello, [Your Name]!' to the console. Call the method to see the output.
Show Solution
def say_hello
puts 'Hello, Alice!'
end
say_hello # Output: Hello, Alice!Step 2: Step 2: Using Parameters in Methods
Parameters allow you to pass data into a method. You define parameters in the method definition and pass arguments when calling the method. Parameters make methods more flexible and reusable.
def greet(name)
puts "Hello, #{name}!"
end
greet('Alice') # Output: Hello, Alice!
greet('Bob') # Output: Hello, Bob!Practice Exercise
Create a method called calculate_area that takes two parameters, length and width, and prints the area of a rectangle. Call the method with different values.
Show Solution
def calculate_area(length, width)
area = length * width
puts "The area is #{area}"
end
calculate_area(5, 10) # Output: The area is 50
calculate_area(3, 7) # Output: The area is 21Step 3: Step 3: Using Optional Arguments
Ruby allows you to define optional arguments by providing default values. If an argument is not provided when the method is called, the default value is used.
def greet(name = 'Guest')
puts "Hello, #{name}!"
end
greet # Output: Hello, Guest!
greet('Alice') # Output: Hello, Alice!Practice Exercise
Write a method called order_coffee that takes two optional arguments: size (default: 'medium') and type (default: 'latte'). The method should print the order details. Call the method with different combinations of arguments.
Show Solution
def order_coffee(size = 'medium', type = 'latte')
puts "One #{size} #{type}, please!"
end
order_coffee # Output: One medium latte, please!
order_coffee('large', 'cappuccino') # Output: One large cappuccino, please!Step 4: Step 4: Returning Values from Methods
Methods can return values using the return keyword. If no return is specified, the method returns the value of the last executed expression. Return values allow you to use the result of a method in other parts of your program.
def add(a, b)
return a + b
end
sum = add(3, 5)
puts sum # Output: 8Practice Exercise
Create a method called calculate_discount that takes two parameters: price and discount_percentage. The method should return the discounted price. Print the result after calling the method.
Show Solution
def calculate_discount(price, discount_percentage)
discount = price * (discount_percentage / 100.0)
price - discount
end
discounted_price = calculate_discount(100, 20)
puts discounted_price # Output: 80.0Step 5: Step 5: Combining Parameters, Optional Arguments, and Return Values
Now that you understand the basics, let's combine these concepts to create more complex methods. You can define methods with multiple parameters, optional arguments, and return values to solve real-world problems.
def calculate_total(price, quantity = 1, tax_rate = 0.1)
subtotal = price * quantity
total = subtotal + (subtotal * tax_rate)
return total
end
total_cost = calculate_total(50, 2)
puts total_cost # Output: 110.0Practice Exercise
Write a method called generate_invoice that takes three parameters: item_name, price, and quantity (default: 1). The method should calculate the total cost including a 10% tax and return a formatted invoice string. Call the method and print the invoice.
Show Solution
def generate_invoice(item_name, price, quantity = 1)
subtotal = price * quantity
tax = subtotal * 0.1
total = subtotal + tax
"Invoice:\nItem: #{item_name}\nQuantity: #{quantity}\nSubtotal: $#{subtotal}\nTax: $#{tax}\nTotal: $#{total}"
end
invoice = generate_invoice('Laptop', 1000, 2)
puts invoice
# Output:
# Invoice:
# Item: Laptop
# Quantity: 2
# Subtotal: $2000
# Tax: $200
# Total: $2200Step 6: Step 6: Using Variable-Length Arguments
Ruby allows you to define methods that accept a variable number of arguments using the splat operator (*). This is useful when you don't know how many arguments will be passed to the method.
def sum(*numbers)
numbers.sum
end
puts sum(1, 2, 3) # Output: 6
puts sum(4, 5, 6, 7, 8) # Output: 30Practice Exercise
Create a method called average that takes a variable number of arguments and returns the average of the numbers. Test the method with different sets of numbers.
Show Solution
def average(*numbers)
numbers.sum / numbers.size.to_f
end
puts average(1, 2, 3) # Output: 2.0
puts average(4, 5, 6, 7, 8) # Output: 6.0Step 7: Step 7: Real-World Application - Building a Simple Calculator
Let's apply everything you've learned to build a simple calculator. The calculator will have methods for addition, subtraction, multiplication, and division, with optional parameters and return values.
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
def multiply(a, b)
a * b
end
def divide(a, b)
a / b
end
puts add(10, 5) # Output: 15
puts subtract(10, 5) # Output: 5
puts multiply(10, 5) # Output: 50
puts divide(10, 5) # Output: 2Practice Exercise
Extend the calculator to include a method called calculate that takes three parameters: operation, a, and b. The method should perform the specified operation and return the result. Test the method with different operations.
Show Solution
def calculate(operation, a, b)
case operation
when 'add'
a + b
when 'subtract'
a - b
when 'multiply'
a * b
when 'divide'
a / b
else
'Invalid operation'
end
end
puts calculate('add', 10, 5) # Output: 15
puts calculate('subtract', 10, 5) # Output: 5
puts calculate('multiply', 10, 5) # Output: 50
puts calculate('divide', 10, 5) # Output: 2
puts calculate('power', 10, 5) # Output: Invalid operationStep 8: Step 8: Advanced Challenge - Building a Temperature Converter
For a more advanced challenge, let's build a temperature converter that can convert between Celsius and Fahrenheit. The converter will have methods for both conversions and will use optional arguments and return values.
def celsius_to_fahrenheit(celsius)
(celsius * 9 / 5) + 32
end
def fahrenheit_to_celsius(fahrenheit)
(fahrenheit - 32) * 5 / 9
end
puts celsius_to_fahrenheit(0) # Output: 32.0
puts fahrenheit_to_celsius(32) # Output: 0.0Practice Exercise
Extend the temperature converter to include a method called convert_temperature that takes two parameters: temperature and unit (default: 'celsius'). The method should convert the temperature to the other unit and return the result. Test the method with different temperatures and units.
Show Solution
def convert_temperature(temperature, unit = 'celsius')
if unit == 'celsius'
(temperature * 9 / 5) + 32
else
(temperature - 32) * 5 / 9
end
end
puts convert_temperature(0) # Output: 32.0
puts convert_temperature(32, 'fahrenheit') # Output: 0.0Sign in to take Cornell notes on this lesson — they save automatically and stay with your account.