iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Methods

Ruby methods are pleasant: implicit return, blocks, optional parens, default args, keyword args, splats. The same flexibility makes Ruby APIs read like prose.

Method definitions + dispatch

EXAMPLE
# 1) Plain method
def greet(name)
    "Hello, #{name}"          # last expression is returned
end

puts greet 'Ada'              # parens optional

# 2) Default + keyword arguments
def greet(name, prefix: 'Hi', suffix: '!')
    "#{prefix}, #{name}#{suffix}"
end

greet('Ada')
greet('Bo', prefix: 'Hello', suffix: '.')

# 3) Required keyword args (no default)
def config(host:, port:)
    "#{host}:#{port}"
end

config(host: 'localhost', port: 8080)

# 4) Splat args — positional varargs
def sum(*xs)
    xs.reduce(0, :+)
end

sum(1, 2, 3, 4)               # 10
nums = [1, 2, 3]
sum(*nums)                     # splat at call site

# 5) Double splat — keyword varargs
def trace(event, **meta)
    puts "#{event}: #{meta.inspect}"
end

trace(:login, user_id: 42, ip: '1.2.3.4')

# 6) Blocks — first-class without being passed explicitly
def each_with_log(arr)
    arr.each do |x|
        puts "visit #{x}"
        yield x if block_given?
    end
end

each_with_log([1, 2, 3]) { |x| puts "squared: #{x * x}" }

# 7) &block — capture block as a Proc
def retry(times = 3, &block)
    times.times do
        return block.call
    rescue
        next
    end
end

retry { fetch_data }

# 8) Single-method endless def (Ruby 3+)
def double(x) = x * 2
def square(x) = x ** 2

# 9) Pattern matching in defs (Ruby 3+)
def describe(value)
    case value
    in Integer  then 'int'
    in String   then 'string'
    in [_, _]   then 'pair'
    in { name: String => n } then "named #{n}"
    end
end

# 10) Private / protected
class Bank
    def transfer(amount); validate(amount); end
    private def validate(n) ; raise unless n.positive? ; end
end

Why it matters

Endless def (def name(args) = expr) makes one-line helpers shine. Combine with keyword args + pattern matching, and Ruby’s most idiomatic code stays declarative without losing flexibility.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
def greet(name = 'world')
    "Hello, #{name}"
end
puts greet            # 'Hello, world'
puts greet('Ada')     # 'Hello, Ada'
Try it Yourself »

Exercise

Define a method named greet.

greet 'hi' end

Discussion

Loading…