Functions in Ruby

Functions are central in Ruby. We’ll learn about functions with a few different examples.

# Here's a function that takes two integers and returns
# their sum as an integer.
def plus(a, b)
  # Ruby automatically returns the value of the last expression,
  # so we don't need an explicit return statement.
  a + b
end

# In Ruby, you can define methods with multiple parameters
# without specifying their types.
def plus_plus(a, b, c)
  a + b + c
end

# Call a function just as you'd expect, with name(args).
res = plus(1, 2)
puts "1+2 = #{res}"

res = plus_plus(1, 2, 3)
puts "1+2+3 = #{res}"

To run the program, save it as functions.rb and use the ruby command:

$ ruby functions.rb
1+2 = 3
1+2+3 = 6

There are several other features to Ruby functions. One is multiple return values, which we’ll look at next.

Key differences from the original example:

  1. In Ruby, we use the def keyword to define functions instead of func.
  2. Ruby doesn’t require explicit type declarations for parameters or return values.
  3. Ruby automatically returns the value of the last expression in a function, so we don’t need explicit return statements.
  4. We use puts for printing output instead of fmt.Println.
  5. String interpolation in Ruby is done with #{variable} inside double quotes.
  6. Ruby doesn’t have a separate main function. The code outside of function definitions is executed when the script runs.

These changes reflect Ruby’s syntax and idiomatic expressions while maintaining the structure and explanations of the original example.