AnyCompiler

Methods

Methods are defined with def ... end and can take default argument values, evaluated only when the caller omits that argument. The behavioral detail every other language on this site requires explicitly: a Ruby method's return value is simply whatever its last evaluated expression was. return exists and works, but it's an escape hatch for early exits, not something every method needs.

def square(n)
  n * n
end

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

puts square(5)
puts greet
puts greet("Ruby")
Output
25
Hello, stranger!
Hello, Ruby!

square never writes return n * n — the method's body is one expression, n * n, and that expression's value is automatically what square(5) evaluates to. This is a genuine behavioral difference from Python, JavaScript, Rust, Go, Java, and every other language on this site, all of which require an explicit return (or, for single-expression arrow functions in JS, a different syntax entirely) to send a value back. Next: blocks, procs, and lambdas — Ruby's own, distinctive mechanism for passing a chunk of code into a method call.

Practice exercise

Write def add(a, b) that returns a + b with no return keyword, then print add(15, 27).