» Quick Introduction to Ruby » 1. Basics » 1.5 Functions

Functions

In Ruby, functions are defined using the def keyword. They are often referred to as methods since everything is an object in Ruby.

The basic syntax for defining a function:

def method_name(parameter1, parameter2, ...)
  # Function body
  # Code to be executed when the function is called
end

Here's a basic method with one parameter:

def triple(x)
    x * 3
end

Functions implicitly return the value of the last statement.

You can also use an explicit return:

def square(x)
   return x * x
end

Parentheses around function arguments are often optional in various situations.

a = square 5
puts a # => 25

Variadic Arguments

You can define methods that accept a variable number of arguments using the splat operator (*). This allows a method to accept any number of arguments, and these arguments will be gathered into an array.

def sum(*numbers)
  total = 0
  numbers.each { |num| total += num }
  total
end

# Call the method with different numbers of arguments
result1 = sum(1, 2, 3)
result2 = sum(4, 5, 6, 7, 8)

puts result1  # => 6
puts result2  # => 30

Multiple Return Values

A method can return multiple values by using an array, a hash, or the special return syntax.

def multiple_values
  return 1, "hello", true
end

result_array = multiple_values
puts result_array.inspect  # => [1, "hello", true]


a, b, c = multiple_values
puts a, b, c
# 1
# hello
# true

yield

The yield keyword is used within a method to invoke a block that is passed to that method. It allows a method to execute a block of code at a specific point within its implementation. The block can receive parameters and is executed in the context of the method.

def greet
  puts "Hello!"
  yield
  puts "Goodbye!"
end

greet do
  puts "Welcome to the Ruby world!"
end

# Hello!
# Welcome to the Ruby world!
# Goodbye!

You can have multiple yields in the function body.

def whereareyou
   yield
   yield
   yield
end

whereareyou {puts "where are you?"}

# where are you?
# where are you?
# where are you?

You can also pass parameters to the block using yield:

def calculate
  x = 5
  y = 10
  result = yield(x, y)
  puts "Result: #{result}"  # => Result: 50
end

calculate do |a, b|
  a * b
end

Code Challenge

Write a Ruby function named fizzbuzz that takes an integer as input and performs the following actions:

  • If the number is divisible by 3, print "Fizz."
  • If the number is divisible by 5, print "Buzz."
  • If the number is divisible by both 3 and 5, print "FizzBuzz."
  • If none of the above conditions apply, print the number itself.
Loading...
> code result goes here
Prev
Next