GGistDev

Methods in Ruby

Define behavior with flexible parameters; last expression is the return value.

Defining methods and return

Methods return the last evaluated expression; return is optional.

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

greet("Ava")  # => "Hi, Ava!"

Positional, defaults, and splats

def add(a, b = 0)
  a + b
end

def sum(*nums)
  nums.reduce(0, :+)
end

add(3)        # => 3
sum(1,2,3)    # => 6

Keyword arguments and double splat

Required and optional keywords; **kwargs captures extra keywords.

def config(host:, port: 80, **opts)
  { host:, port:, **opts }
end

config(host: "localhost")            # => {host:"localhost", port:80}
config(host: "localhost", ssl: true) # => {host:"localhost", port:80, ssl:true}

Block parameters and yield

Pass blocks implicitly or explicitly with &block.

def with_logging
  puts "start"
  result = yield 42 if block_given?
  puts "done"
  result
end

with_logging { |n| n * 2 }  # prints start/done, returns 84

Forwarding arguments (Ruby 2.7+)

The ... syntax forwards all positional, keyword, and block arguments.

def wrapper(...)
  target(...)
end

Predicate and bang methods

Predicate methods (ending with ?) return booleans. Bang methods (!) usually mutate or are the "dangerous" variant.

"".empty?      # => true
name = "ruby"
name.upcase!    # mutates string to "RUBY"

Visibility

public (default), protected (callable by instances of same class), private (no explicit receiver).

class Account
  def transfer_to(other, amt)
    debit(amt)
    other.credit(amt)   # allowed: protected
  end

  protected
  def credit(amt); @bal += amt end

  private
  def debit(amt); @bal -= amt end
end

Summary

  • Use defaults, splats, and keywords to design ergonomic APIs
  • Accept blocks implicitly; forward with ... when wrapping other methods
  • Choose visibility to enforce encapsulation