Functions in Ruby
Functions are central in Ruby. We’ll learn about functions with a few different examples.
To run the program, save it as functions.rb
and use the ruby
command:
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:
- In Ruby, we use the
def
keyword to define functions instead of func
. - Ruby doesn’t require explicit type declarations for parameters or return values.
- Ruby automatically returns the value of the last expression in a function, so we don’t need explicit
return
statements. - We use
puts
for printing output instead of fmt.Println
. - String interpolation in Ruby is done with
#{variable}
inside double quotes. - 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.