Title here
Summary here
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:
def
keyword to define functions instead of func
.return
statements.puts
for printing output instead of fmt.Println
.#{variable}
inside double quotes.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.