Methods & Implicit Returns

💎 Ruby Lesson 8 Beginner

Methods modularize code blocks. Ruby methods support default parameters, named keyword arguments, and implicit return values.

1 Explicit vs. Implicit Returns

In Ruby, **the return keyword is optional**. A method automatically returns the value of the last evaluated statement in its body. This makes Ruby code exceptionally clean and concise.

2 Parameter Configurations Code

Let's run a program illustrating methods, default arguments, and implicit returns:

Ruby — Methods ▶ Run Code
# Method with default arguments & implicit return (no 'return' keyword needed)
def calculate_price(price, tax_rate = 0.08)
  price + (price * tax_rate) # Last statement is returned automatically
end

# Keyword arguments
def print_user(name:, role: "Guest")
  puts "User: #{name}, Role: #{role}"
end

final_price = calculate_price(100.0)
puts "Total Price: $#{final_price}"

print_user(name: "Charlie")
3 Code Challenge
Challenge: Write a method called `is_even?` that accepts an integer and implicitly returns `true` or `false`. Note that idiomatic Ruby methods returning booleans end with a question mark.