Working with Functions and Methods in Ruby

February 29, 2024

In Ruby, functions and methods are essential for organizing and modularizing code. They allow you to encapsulate a set of instructions that can be reused throughout your program. This lesson will cover the creation and usage of functions and methods in Ruby, explaining the concept of parameters, return values, and the importance of modularizing code through functions.

Defining Functions in Ruby

To define a function in Ruby, you use the def keyword followed by the function name and any parameters it may take. Here’s a simple example:

def greet(name)
  puts 'Hello, ' + name
end

In this example, greet is the function name, and name is the parameter it takes. The function body contains the instructions to greet the provided name.

Calling Functions

Once a function is defined, you can call it elsewhere in your code by simply using its name and providing the necessary arguments:

greet('Alice')
# Output: Hello, Alice

Return Values

Functions in Ruby can return values using the return keyword. Here’s an example of a function that calculates the square of a number and returns the result:

def square(num)
  return num * num
end
result = square(5)
puts result
# Output: 25

Methods in Ruby

In Ruby, functions that are associated with a specific object or class are called methods. They are defined within the context of a class and can be called on instances of that class. Here’s an example of a simple method within a class:

class Dog
  def bark
    puts 'Woof!'
  end
end
fido = Dog.new
fido.bark
# Output: Woof!

Conclusion

Functions and methods are powerful tools for organizing and reusing code in Ruby. By encapsulating specific tasks into functions and methods, you can create more modular and maintainable code. Understanding how to define, call, and work with functions and methods is fundamental to becoming proficient in Ruby programming.