Table of Contents
Share this Resource

Ruby Methods

Ruby Methods are a fundamental aspect of Ruby programming, acting as reusable blocks of code designed to perform specific tasks. Ruby encapsulates code within methods and enables more precise, organised programming. Methods in Ruby can take parameters and return values and offer flexibility through features like default and variable arguments.

They are easily invoked by their name, enhancing the readability and maintainability of code. Understanding how to define and use methods is essential for any Ruby programmer, as they play a critical role in structuring code and implementing functionality efficiently and effectively. Read this blog to learn more!

What is the Ruby Method?

A Ruby Method is a set of expressions that returns a value. In Ruby, methods can bundle one or more repeatable statements into a single unit. Ruby Methods are defined using the ‘def’ keyword and the method name. They can take arguments and return a value. Methods in Ruby are crucial for organising and reusing code, making it more readable and maintainable.

Ruby Methods can yield blocks, providing a powerful way to abstract functionality and customise behaviour. The last evaluated statement in the method is automatically returned by the method unless an explicit return statement is used. This feature contributes to Ruby's expressive and concise nature. Let’s see how:

Syntax

The basic syntax for defining a method in Ruby is:

def method_name(arguments)

# code to be executed

end

The parentheses can be omitted if the method doesn't take any arguments. Arguments can be defined with default values, and Ruby also supports splat arguments for a variable number of arguments.

Illustrative example

Consider a simple method that calculates the sum of two numbers:

def sum(a, b)

a + b

end

puts sum(5, 3) # Output: 8

In this example, ‘sum’ is the method name, and ‘a’ and ‘b’ are parameters. The method adds these two parameters and returns their sum. The ‘puts sum(5, 3)’ line calls the method with arguments 5 and 3 and prints the result, which is 8. Here, both ‘a’ and ‘b’ belong to the Ruby Data Types category of Integers. This example illustrates the basic structure and usage of a method in Ruby.

Ruby Programming Course

Return values from Methods

In Ruby, every method returns a value. The returned value is the result of the last evaluated expression in the method unless an explicit ‘return’ statement is used to specify a different return value. This implicit return feature is a distinctive aspect of Ruby, making the language expressive and concise.

For example, consider a method that calculates the square of a number:

def square(number)

number * number

end

In this method, ‘number * number’ is the last evaluated expression, and its result is automatically returned when the method is called. Therefore, ‘square(4)’ would return 16.

However, Ruby also allows using the return keyword to specify the return value explicitly. This is particularly useful when you need to return early from a method:

def check_positive(number)

return 'Number is zero' if number == 0

number > 0 ? 'Positive' : 'Negative'

end

In this example, if ‘number’ is zero, the method returns 'Number is zero' immediately. Otherwise, it evaluates the ternary operation and returns 'Positive' or 'Negative' based on the number's value. The explicit ‘return’ is useful for branching and conditional logic within methods.

Become a professional in Programming with our Programming Training – register now!

Ruby return Statement

In Ruby, the ‘return’ statement explicitly specifies the value to be returned by a method. If no ‘return’ statement is used, a Ruby Method automatically returns the value of the last evaluated expression

Syntax

In Ruby, the ‘return’ statement exits a method and returns a specific value to the method's caller. The syntax for the return statement is straightforward: ‘return’ followed by the value or expression you want to return. If no value or expression follows ‘return’, the method returns ‘nil’.

def method_name

  # ...

  return value

end

The ‘return’ keyword is optional when it appears at the end of a method because Ruby implicitly returns the value of the last evaluated expression.

Illustrative example

Consider a method that determines the type of a given number:

def number_type(num)

  return 'positive' if num > 0

  return 'negative' if num < 0

  'zero'

end

puts number_type(10)  # Output: positive

puts number_type(-5)  # Output: negative

puts number_type(0)   # Output: zero

In this example, ‘return’ is used to exit the method immediately with a specific string when a condition is met. The method implicitly returns ' zero ' if none of the conditions are met.

Methods within classes

In Ruby, methods are commonly defined within classes. These methods, known as instance methods, are associated with instances of the class. They can access and modify the state of the object to which they belong.

The ‘def’ keyword is used inside a class definition to define a method within a class. The process can then be called on instances of that class.

Here's an example:

class Calculator

  def add(a, b)

    a + b

  end

end

calc = Calculator.new

puts calc.add(5, 3)  # Output: 8

In this example, ‘add’ is an instance method of the ‘Calculator’ class. It adds two numbers and returns the result. An instance of ‘Calculator’ is created, and the ‘add’ method is called on it.

Ruby alias statement

In Ruby, the ‘alias’ statement creates a new name or alias for an existing method or global variable, allowing the original name and the alias to be used interchangeably. This feature helps enhance readability or modify behaviour while maintaining compatibility with existing code.

Syntax

Ruby's ‘alias’ statement creates an alias for a method or global variable. The syntax is ‘alias new_name old_name’. It allows a method or global variable to be referred to by two names.

alias new_method_name old_method_name

Illustrative example

class Greeting

  def hello

    "Hello!"

  end

  alias greet hello

end

g = Greeting.new

puts g.hello   # Output: Hello!

puts g.greet   # Output: Hello!

In this example, the ‘greet’ method is an alias for the ‘hello’ method in the ‘Greeting’ class. Both ‘g.hello’ and ‘g.greet’ call the same method.

Ruby undef Statement

In Ruby, the ‘undef’ statement is used to undefine a method defined in a class, rendering the method inaccessible from instances of that class. This statement is useful for modifying or restricting the interface of a class, especially when subclassing or mixing modules.

Syntax

undef method_name

Illustrative example

class Example

  def greet

    "Hello!"

  end

  def farewell

    "Goodbye!"

  end

  undef farewell

end

e = Example.new

puts e.greet      # Output: Hello!

puts e.farewell # This will raise a NoMethodError

In this example, the ‘farewell’ method is undefined using the ‘undef’ statement. Trying to call ‘farewell’ on an instance of ‘Example’ will result in a ‘NoMethodError’, as the method no longer exists in the class.

Do you want to learn more about Python? Then register now for our Python Course!

user
Nilotpal Sarmah

Senior Content Writer

Nilotpal Sarmah is a Senior Content Writer with 11+ years of overall experience spanning engineering, operations and content development. His technical knowledge and extensive writing experience enable him to simplify specialised topics across IT and Tech, Business Skills, Project Management, Health and Safety, and ISO and Compliance.

View Detail icon
cross

Upgrade Your Skills. Save More Today.

superSale Unlock up to 40% off today!

WHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.