CodeToLive

Functions in Ruby

Functions in Ruby are reusable blocks of code that perform a specific task. They help in organizing code and avoiding repetition.

Defining a Function

Functions in Ruby are defined using the def keyword.


def greet(name)
    puts "Hello, #{name}!"
end

greet("Alice")
      

Returning Values

Functions can return values using the return keyword.


def add(a, b)
    return a + b
end

result = add(5, 10)
puts "Sum: #{result}"
      

Default Arguments

You can provide default values for function arguments.


def greet(name = "Guest")
    puts "Hello, #{name}!"
end

greet
greet("Alice")
      

Variable-Length Arguments

Use *args to accept a variable number of arguments.


def sum(*numbers)
    numbers.sum
end

puts sum(1, 2, 3)
puts sum(4, 5, 6, 7)
      

Lambda Functions

Lambda functions are anonymous functions that can be passed around as objects.


double = ->(x) { x * 2 }
puts double.call(5)
      

Recursion

A function can call itself, which is known as recursion.


def factorial(n)
    return 1 if n <= 1
    n * factorial(n - 1)
end

puts factorial(5)
      

Interactive Code Examples

Try running these examples in your Ruby environment to see how they work!


# Interactive Example
puts "Enter a number:"
num = gets.chomp.to_i
puts "Factorial: #{factorial(num)}"
      

Practice Problems

Test your understanding with these practice problems:

  1. Write a Ruby function to calculate the area of a circle given its radius.
  2. Write a Ruby function to check if a string is a palindrome.
  3. Write a Ruby function to find the largest number in an array.
Next: Classes and Objects