RUBY / CHAPTER 03

Methods, arguments, and blocks

Beginner

Write reusable operations with clear return and calling rules.

By the end of this chapter

  • Trace implicit and explicit returns
  • Separate keyword arguments from positional meaning
  • Pass a block to customize an operation

The idea

A Ruby method normally returns its last evaluated expression, while return can end the method earlier. This makes short transformation methods natural, but printing at the end changes the result to the printing method’s return value. State the result contract before choosing the final expression. Keyword arguments can make related settings clearer than a sequence of unnamed booleans or numbers.

A block supplies behavior to a method. The receiving method can invoke it with yield, allowing iteration or formatting logic to be supplied by the caller. Blocks can refer to surrounding local variables, so watch for changes to captured state. Prefer a simple block when behavior is used once, and extract a named method when the operation deserves a reusable concept or independent tests.

Ruby example
def format_count(count, prefix: "Items")
  "#{prefix}: #{count}"
end

def transform(value)
  yield value
end

puts transform(4) { |n| format_count(n * 2, prefix: "Ready") }
Result
Ready: 8

The block receives four and returns a formatted doubled value. Both methods return their final expressions without an explicit return statement.

Try it yourself

Write a method that takes a collection and a block, returning the first transformed value that is not nil.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What value does this method return for title("api")?
def title(text)
  text.upcase
end