RB Ruby

Ruby: Methods

What you will learn

How to define methods with def, Ruby's implicit return, default arguments, and the distinction between methods ending in ? and !.

Defining a method

def greet(name)
  "Hello, #{name}!"
end

puts greet("Alice")  # Hello, Alice!

Methods are defined with def, closed with end. The last expression in the method is automatically returned — no return keyword needed.

Default arguments

def power(base, exp = 2)
  base ** exp
end

puts power(3)    # 9  (exp defaults to 2)
puts power(3, 3) # 27

Implicit return vs explicit return

def add(a, b)
  a + b          # implicit — a + b is the last expression
end

def max(a, b)
  return a if a > b   # explicit early return
  b                    # implicit fallback
end

Use return when you need to exit early. Let the last expression be the return for simple cases.

Predicate methods (?) and bang methods (!)

By convention: - Methods ending in ? return a boolean (Array#empty?, String#include?) - Methods ending in ! are destructive / modify in place (Array#sort!, String#upcase!)

"hello".empty?          # false
[1, 2, 3].include?(2)  # true

name = "alice"
name.upcase           # "ALICE" — returns new string
name                  # "alice" — original unchanged
name.upcase!          # "ALICE" — modifies in place
name                  # "ALICE" — original changed

Common mistakes

  • Using return when it's unnecessary — the last expression is returned automatically
  • Defining a method with def but forgetting end — SyntaxError
  • Using parentheses everywhere — Ruby doesn't require them: greet "Alice" works
  • Forgetting that return exits the method immediately — code after it won't run

Quick check below!