Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Implicit return value

If there is no explicit return statement then the result of the last statement executed in the function will be returned from the function.

def add(x, y)
  z = x + y
end

res = add(2, 3)
puts res # 5
def cond(x)
  if x > 5
    return x
  end
end

[3, 6].each { |value|
  puts value
  res = cond(value)
  puts res
  puts typeof(res)

  # puts res+1
  # Error: undefined method '+' for Nil (compile-time type is (Int32 | Nil))

  if !res.nil?
    puts res + 1
  end
}
3

(Int32 | Nil)
6
6
(Int32 | Nil)
7