Methods and Arguments

Methods and Arguments in Ruby: --- A dispensing pharmacy has one intake window and a stack of printed forms beside it.


The Analogy: The Prescription Intake Window

A dispensing pharmacy has one intake window and a stack of printed forms beside it. The form is the contract between the person handing something in and the pharmacist behind the glass. Some boxes have to be filled or the form comes straight back over the counter: patient name, drug, dose. Some boxes have a value already printed on them, so leaving them blank means you accept what is printed: quantity thirty unless you write something else. Some boxes are labelled by name rather than by position, so it does not matter which order you fill them in, only that you write the value in the box with the right label on it.

A Ruby method signature is that form, and it is just as specific. def dispense(drug, quantity = 30, refills: 0) says one box must be filled in the first position, one box is optional with thirty printed in it, and one box is filled by name. The caller and the method never have to negotiate. Everything about what may be handed over is written once, in the signature, and Ruby enforces it at the window rather than somewhere inside the compounding room.

The window also has two extras that make the form flexible without making it vague. There is a wide unlabelled tray for however many loose items you want to hand across, which is the splat *items; and a notes area for any labelled remarks the form did not anticipate, which is the double splat **flags. And clipped to the top of every form there can be an instruction slip -- do this to each item as you go -- which is the block. The slip is not a box on the form. It rides along with it, and the pharmacist decides whether and how often to read it.

The failure modes are the ones a real counter sees. Hand over a form with the drug box empty and it is refused immediately, at the window, which is Ruby raising ArgumentError at the call site rather than handing you a nil that surfaces three rooms away. Hand over five loose slips in a heap and hope the clerk reads them in the right order, and eventually somebody reads them in the wrong order: that is a method with five positional parameters, and the fix is to label the boxes. Write a remark in the notes area when you meant to fill a labelled box, and it is filed as a remark and quietly ignored, because a typo in a keyword name lands in **flags instead of being refused. And clip an instruction slip to a form nobody reads slips from, and nothing happens at all -- or worse, reach for a slip that was never clipped on, which is what LocalJumpError means.


Syntax or Core Structure

Every kind of box on the form, in one file. Nothing here is exotic; this is the vocabulary you will use in every method you write.

# intake.rb -- one window, several kinds of form.

def label(drug, quantity = 30)
  "#{drug} x#{quantity}"
end

def dispense(drug, quantity: 30, refills: 0, generic: true)
  form = generic ? "generic" : "brand"
  "#{drug} x#{quantity} #{form} refills=#{refills}"
end

def total_units(*counts)
  counts.sum
end

def stamp(**flags)
  flags.keys.sort.map { |k| "#{k}=#{flags[k]}" }.join(" ")
end

def each_slip(slips)
  return to_enum(:each_slip, slips) unless block_given?

  slips.each_with_index { |slip, i| yield(i + 1, slip) }
  slips.size
end

def dispensable?(quantity)
  quantity.positive?
end

def normalise!(text)
  text.strip!
  text
end

# A default is printed on the form; supplying a value overrides it.
puts label("amoxicillin")
puts label("amoxicillin", 21)

# Keyword boxes are filled by name, in any order, and may be left blank.
puts dispense("metformin")
puts dispense("metformin", refills: 3, quantity: 60)
puts dispense("metformin", generic: false)

# The splat tray takes any number of loose items, including none.
puts total_units(30, 21, 14)
puts total_units

# The double splat takes any labelled remark at all.
puts stamp(window: 2, verified: true, clerk: "kb")

# A block rides along with the form rather than being a box on it.
handed = each_slip(["amoxicillin x21", "metformin x60"]) do |n, slip|
  puts "slip #{n}: #{slip}"
end
puts "handed #{handed}"
puts each_slip(["a", "b"]).class

# Naming conventions: ? asks, ! is the dangerous twin.
puts dispensable?(21)
puts dispensable?(0)

messy = "  ranitidine  "
puts normalise!(messy).inspect
puts messy.inspect

Output:

amoxicillin x30
amoxicillin x21
metformin x30 generic refills=0
metformin x60 generic refills=3
metformin x30 brand refills=0
65
0
clerk=kb verified=true window=2
slip 1: amoxicillin x21
slip 2: metformin x60
handed 2
Enumerator
true
false
"ranitidine"
"ranitidine"

Two lines here are worth more than the rest. dispense("metformin", refills: 3, quantity: 60) fills the boxes out of order and Ruby does not care, because keyword arguments are matched by name; the same call with positional parameters would have needed you to remember that quantity comes before refills, and would have accepted the two swapped without a word of complaint. And total_units with no arguments at all prints 0 rather than raising, because a splat that receives nothing is an empty Array, and [].sum is zero.

The last pair of lines is the ! convention doing what the convention promises. normalise! was handed the same String object that messy refers to, strip! changed that object in place, and so printing messy afterwards shows the stripped value. Ruby did not enforce any of that: the bang is a note to the reader, not a rule the interpreter knows about, and the same is true of the ? on dispensable?. The one suffix Ruby does treat specially is =, which makes a method a setter and makes the assignment expression evaluate to the right-hand side rather than to whatever the setter returned.


Technical Depth: What The Window Will And Will Not Accept

The Six Kinds Of Parameter

FormHow you declare itWhat the caller must doWhat happens when it is left out
required positionaldrugsupply it, in positionArgumentError at the call site
optional positionalquantity = 30nothingthe default expression is evaluated
required keyworddose:supply it, by nameArgumentError at the call site
optional keywordrefills: 0nothingthe default expression is evaluated
splat*itemsnothingitems is an empty Array
double splat**flagsnothingflags is an empty Hash
block&slipnothingslip is nil, and a bare yield raises LocalJumpError

Order in the signature is fixed: required positionals, optional positionals, splat, keywords in any order, double splat, block. An optional positional cannot follow a splat, because nothing would tell Ruby which argument was meant for which.

Defaults Are Expressions, Not Constants

A default is a piece of code that runs when the argument is missing, at call time, once per call, left to right. That means a later default can see an earlier parameter, and that a mutable default is rebuilt on every call rather than shared.

def receipt(drug, quantity = 30, note = "#{drug} standard #{quantity}")
  "#{drug} #{quantity} :: #{note}"
end

puts receipt("codeine")
puts receipt("codeine", 14)
puts receipt("codeine", 14, "split dose")

COUNTER = []

def tick(stamp = COUNTER.size)
  COUNTER << stamp
  stamp
end

puts tick
puts tick
puts tick
puts COUNTER.inspect

Output:

codeine 30 :: codeine standard 30
codeine 14 :: codeine standard 14
codeine 14 :: split dose
0
1
2
[0, 1, 2]

The note default reads both drug and quantity, which only works because defaults are evaluated left to right after the supplied arguments have been bound. The tick method makes the timing visible: COUNTER.size is not frozen at the moment the method was defined, it is re-evaluated on every call that omits the argument, which is why the three calls print 0, 1 and 2.

Refusals Happen At The Window

def compound(drug, dose:, vehicle: "syrup")
  "#{drug} #{dose} in #{vehicle}"
end

attempts = [
  -> { compound("prednisolone", dose: "5mg") },
  -> { compound("prednisolone") },
  -> { compound(dose: "5mg") },
  -> { compound("prednisolone", "5mg") },
  -> { compound("prednisolone", dose: "5mg", flavour: "cherry") },
]

attempts.each_with_index do |attempt, i|
  result = begin
    attempt.call
  rescue ArgumentError => e
    "refused (#{e.class})"
  end
  puts format("attempt %d  %s", i + 1, result)
end

Output:

attempt 1  prednisolone 5mg in syrup
attempt 2  refused (ArgumentError)
attempt 3  refused (ArgumentError)
attempt 4  refused (ArgumentError)
attempt 5  refused (ArgumentError)

Four different mistakes, one exception class. Attempt 2 omitted a required keyword, attempt 3 the required positional, attempt 4 passed a second positional to a method that accepts one, and attempt 5 passed a keyword the signature never mentioned. All four were caught at the boundary, before a line of the body ran. The code prints e.class rather than e.message because the wording of these messages has changed between Ruby versions.

Attempt 5 is the one to remember: an unknown keyword is an error only because compound has no ** parameter. Add one and flavour: "cherry" stops being a mistake and becomes data.

Splat And Double Splat Work In Both Directions

The same two stars that collect arguments on the way in will spread a collection back out on the way out. * gathers into an Array in a signature and unpacks an Array at a call site; ** gathers into a Hash and unpacks a Hash.

def bag(*items, **flags)
  "items=#{items.size} flags=#{flags.keys.sort.inspect}"
end

puts bag
puts bag("a", "b")
puts bag("a", urgent: true, window: 3)

order = ["a", "b", "c"]
marks = { urgent: true, window: 3 }
puts bag(*order, **marks)

def three(a, b, c)
  "#{a}-#{b}-#{c}"
end

puts three(*order)

Output:

items=0 flags=[]
items=2 flags=[]
items=1 flags=[:urgent, :window]
items=3 flags=[:urgent, :window]
a-b-c

three(*order) is the useful trick: an Array of exactly three items becomes three positional arguments, and a wrong length raises the same ArgumentError you would have got by writing them out. flags.keys.sort is what keeps the output stable, since a Hash preserves insertion order and printing its keys directly would leak whatever order the caller wrote them in.

What A Method Hands Back

A method returns the value of its last evaluated expression. There is no implicit nil, no required return, and no distinction between a method that "returns something" and one that does not.

def last_expression(n)
  n * 2
end

def early(n)
  return "zero" if n.zero?

  n * 2
end

def conditional_result(n)
  if n.positive?
    "double #{n * 2}"
  end
end

def printed(n)
  puts n
end

def bare_return(_n)
  return
end

def endless(n) = n * 2

puts last_expression(3)
puts early(0)
puts early(3)
puts conditional_result(3)
puts conditional_result(-3).inspect
puts printed(7).inspect
puts bare_return(3).inspect
puts endless(3)

Output:

6
zero
6
double 6
nil
7
nil
6

Three of those lines are traps in disguise. conditional_result(-3) returns nil because an if with no matching branch evaluates to nil, so a method whose whole body is a branchless if silently answers nil for every input you did not think about. printed(7) prints 7 and then returns nil, because that is what puts returns -- which is why the 7 and the nil appear on separate lines and in that order. And bare_return shows that return with no value means return nil, not "return whatever was last computed".

The last definition, def endless(n) = n * 2, is the endless method form added in Ruby 3.0. It is for one-expression methods and nothing else; the moment the body needs two lines, go back to def and end.


Real World Example: The Intake Window For One Morning

Eight scripts came in across a single morning. One method does the dispensing, and every kind of parameter earns its place in its signature: the script is positional, the window number and the pharmacist's initials are required keywords, generic substitution is an optional keyword, and per-drug policy arrives through a double splat.

# intake_window.rb -- one window, one morning, one report.

Script = Struct.new(:minute, :drug, :quantity, :per_day, :unit_pence) do
  def days
    quantity / per_day
  end

  def pence
    quantity * unit_pence
  end

  def clock
    format("%02d:%02d", minute / 60, minute % 60)
  end
end

SCRIPTS = <<~ROWS
  0902 amoxicillin  21 3 12
  0908 metformin    56 2  4
  0915 codeine      30 4  9
  0921 amoxicillin  15 3 12
  0930 prednisolone 20 1 15
  0937 metformin    28 2  4
  0944 codeine      12 4  9
  0950 metformin    56 2  4
ROWS

POLICY = {
  "codeine" => { controlled: true },
  "prednisolone" => { generic: false, taper: true },
}

def parse(text)
  text.lines.map do |line|
    hhmm, drug, quantity, per_day, unit_pence = line.split
    Script.new(hhmm[0, 2].to_i * 60 + hhmm[2, 2].to_i, drug,
               quantity.to_i, per_day.to_i, unit_pence.to_i)
  end
end

def dispense(script, window:, initials:, generic: true, **notes)
  tag = ["w#{window}", initials, generic ? "generic" : "brand"]
  tag.concat(notes.keys.sort.map { |k| "#{k}=#{notes[k]}" })

  format("  %s  %-12s q%-3d %2dd %4dp  %s",
         script.clock, script.drug, script.quantity,
         script.days, script.pence, tag.join(" "))
end

scripts = parse(SCRIPTS)
puts "scripts: #{scripts.size}"

scripts.each_with_index do |script, i|
  policy = POLICY.fetch(script.drug, {})
  puts dispense(script, window: (i % 2) + 1, initials: i.even? ? "kb" : "rd", **policy)
end

by_drug = scripts.group_by(&:drug)
by_drug.keys.sort.each do |drug|
  batch = by_drug[drug]
  puts format("  %-12s n=%d  q=%3d  %4dp",
              drug, batch.size, batch.sum(&:quantity), batch.sum(&:pence))
end

pence = scripts.sum(&:pence)
puts format("total %d items, %dp (%d.%02d)", scripts.size, pence, pence / 100, pence % 100)

controlled = scripts.count { |s| POLICY.fetch(s.drug, {})[:controlled] }
puts "controlled lines: #{controlled}"

Output:

scripts: 8
  09:02  amoxicillin  q21   7d  252p  w1 kb generic
  09:08  metformin    q56  28d  224p  w2 rd generic
  09:15  codeine      q30   7d  270p  w1 kb generic controlled=true
  09:21  amoxicillin  q15   5d  180p  w2 rd generic
  09:30  prednisolone q20  20d  300p  w1 kb brand taper=true
  09:37  metformin    q28  14d  112p  w2 rd generic
  09:44  codeine      q12   3d  108p  w1 kb generic controlled=true
  09:50  metformin    q56  28d  224p  w2 rd generic
  amoxicillin  n=2  q= 36   432p
  codeine      n=2  q= 42   378p
  metformin    n=3  q=140   560p
  prednisolone n=1  q= 20   300p
total 8 items, 1670p (16.70)
controlled lines: 2

The signature of dispense is the design document for this program. script is positional because there is exactly one of it and no reader will ever wonder what the first argument means. window: and initials: are required keywords rather than positionals two and three, which is what stops a caller from swapping a window number and a pair of initials -- a mistake that positional parameters would accept in silence. generic: true carries the common case as a printed default, so seven of the eight calls never mention it. And **notes absorbs whatever per-drug policy the POLICY Hash holds, which is why the two codeine lines carry controlled=true without dispense knowing anything about controlled drugs.

The call site is where the two stars pay off. **policy spreads a Hash back out into keyword arguments, so { generic: false, taper: true } becomes generic: false, taper: true and lands in two entirely different places: generic matches a declared keyword and switches the tag to brand, while taper has no matching keyword and falls into notes. One Hash, one splat, and the signature decides which half of it is configuration and which half is data. When POLICY has no entry for a drug, fetch supplies an empty Hash and **{} contributes nothing at all, so the call reads identically for the plain cases.

Every number in the report can be checked by hand. Pence per script is quantity times unit price -- 21 at 12p is 252p, 56 at 4p is 224p -- and the four per-drug subtotals of 432, 378, 560 and 300 sum to 1670, which is the total line. The 1670 is then split into pounds and pence by integer division and remainder rather than by floating point, so 16.70 is exact rather than nearly right. Ordering is deliberate too: by_drug.keys.sort fixes the four summary lines in alphabetical order instead of the order the drugs first appeared, and notes.keys.sort fixes the order of the trailing tags.

Now the flaw, and it comes straight out of the signature that the rest of this program is built on. **notes accepts absolutely any keyword, which means it also accepts every misspelling of a real one. Write genric: false instead of generic: false in POLICY and nothing is refused: the typo lands in notes, the line prints genric=false as a cheerful little tag, and the drug is dispensed as a generic substitute against an explicit instruction not to. The double splat has converted a signature error -- the kind Ruby catches at the window, as attempt 5 above showed -- into a cosmetic difference in a report nobody proofreads. That is the cost of an open-ended parameter, and the fix is to declare the keywords you actually support and let the unknown ones raise. Three smaller limits are worth naming as well. days uses integer division, so codeine at 30 tablets and four a day prints 7d when the true figure is seven and a half, and that is the number a pharmacist would use to work out the earliest legal refill date. POLICY is keyed by the drug name as a String, so a brand spelling or a trailing space loses the controlled flag entirely and the script dispenses as ordinary stock. And the controlled lines: 2 figure is recomputed from POLICY rather than from what dispense actually did, so if the two ever disagree the report will confidently state the wrong one.


Common Mistakes

  1. Passing a Hash where keyword arguments are expected. In Ruby 3 a Hash and a keyword list are genuinely different things, so opts = { dose: "5mg" } followed by compound("x", opts) raises ArgumentError rather than filling in dose:. Spread it with compound("x", **opts), and remember the reverse too: a method whose last parameter is opts = {} will not accept keyword syntax cleanly.
  1. Using a mutable object as a default and expecting it to be shared. def add(item, into = []) builds a brand new Array on every call that omits the argument, because the default is an expression evaluated at call time. Code written on the assumption that the Array persists between calls will find it empty every time.
  1. Ordering parameters so that the optional ones come first. Ruby matches positionals from the outside in, so def f(a = 1, b) is legal but almost never what you meant, and def f(*items, last) forces the reader to count arguments backwards. Put required positionals first and turn anything genuinely optional into a keyword.
  1. More than about three positional parameters. transfer(a, b, c, d) is unreadable at the call site and every argument is one silent swap away from a wrong answer that still runs. Once the count passes three, convert them to keywords: the call site becomes self-documenting and the swap becomes impossible.
  1. Adding **opts to a signature to be helpful. An open-ended keyword parameter accepts every typo as valid input, so refils: 3 is silently filed as a note rather than refused. Declare the keywords you support and let Ruby reject the rest; add ** only when you genuinely intend to forward unknown options on to another method.
  1. Assuming ? and ! mean something to the interpreter. They are naming conventions and nothing more. A method named valid? may return a String, and a method named save! may quietly do nothing. Ruby will not check, so the promise is yours to keep, and a ? method that returns anything other than true or false will confuse every reader who trusts the convention.
  1. Writing a bare return and expecting the last value. return with no argument returns nil, discarding whatever the method had just computed. A guard clause that ends in a bare return where it meant return result produces a nil that travels a long way before it causes a visible failure.
  1. Forgetting that a setter's return value is thrown away. x.quantity = 500 evaluates to 500 no matter what quantity= returns, so validation, clamping or normalisation inside a setter is invisible to the assigning expression. Read the attribute back if you need the stored value, or use a plainly named method like set_quantity that is allowed to return something.
  1. Calling yield without checking whether a block was given. A method that reaches yield with no block attached raises LocalJumpError, and the call site that triggered it looks entirely ordinary. Guard with block_given?, or better, return an Enumerator when there is no block so the blockless call is useful rather than merely non-fatal.

Best Practices

  • Make the signature the documentation. A reader should be able to tell what a method needs, what is optional and what the defaults are without opening the body, and one line is enough for almost every method you will write.
  • Use required keywords for anything a caller could plausibly get in the wrong order. Two Integers, two Strings or two Booleans side by side in positional slots are a swap waiting to happen; window: 2, initials: "kb" cannot be swapped.
  • Put the common case in a default. If seven calls out of eight want generic: true, print it on the form and let those seven calls stay short, so the eighth call stands out as the exception it is.
  • Prefer raising at the boundary to defending inside. A required parameter that Ruby enforces is better than a nil check three lines into the body, because the error names the call site instead of the method.
  • Keep ** for forwarding, not for flexibility. If your method's job is to pass options through to something else, **opts is exactly right. If its job is to do the work itself, name the keywords.
  • Return the value the caller wants, not nil by accident. Check the last line of every method: a trailing puts, a trailing each or a branchless if all hand back something the caller almost certainly did not ask for.
  • Give an iterator method return to_enum(:name, *args) unless block_given? as its first line. It costs one line and makes your method compose with everything Enumerable offers.
  • Honour the naming conventions strictly, including the part where ! implies a non-bang sibling. A bang method with no safe twin is a method with a warning label and no alternative, which tells the reader nothing.

Practice Exercises

  1. Convert a positional signature to keywords. Write def transfer(from, to, quantity, urgent) and a call that swaps from and to by mistake; show that it runs happily. Now rewrite it with required keywords, make the same mistake, and show what Ruby says. Then add a default so that the non-urgent case does not have to mention urgency at all.
  1. Prove when defaults are evaluated. Write def stamp(at = Time.now.to_i, tag = "t#{at}") and, without printing any clock value, demonstrate three things: that tag can see at, that passing at explicitly changes tag, and that passing tag explicitly leaves at alone. Use a fixed Integer for at in every call so your output is reproducible.
  1. Close the typo hole in the intake window. Replace **notes in dispense with an explicit controlled: false, taper: false pair, then feed it a POLICY entry containing genric: false and show the ArgumentError. Then decide what should happen to a genuinely unknown-but-valid note, and implement whichever answer you argued for.
  1. Build a splat-forwarding wrapper. Write def audited(*args, **kwargs, &block) that logs how many positional arguments and which keyword names it received, then calls dispense with all of them untouched. Confirm that a call through the wrapper produces byte-identical output to the direct call, and explain why &block has to be listed last.