Page Content

Tutorials

Methods In Ruby: The Core Of Object-Oriented Programming

Methods in Ruby

A key idea in Ruby is methods, which are sometimes called functions in other programming languages. A method is a named unit of parameterized code that is connected to one or more objects in Ruby.

Ruby is a totally object-oriented (OO) language, meaning that every method is a genuine method that is connected to at least one object (referred to as the receiver). The primary means by which objects receive and respond to messages are called methods.

Defining Methods

The def keyword is used to define a method, followed by the method name, and the end keyword is used to end the method. In general, method names ought to start with a lowercase letter.

You can also read Hashes in Ruby: Understanding the Key-Value Data Structure

Syntax and Structure

Definition: Between def and end is Ruby code that makes up the method’s body.

Parameters: Following the method name in parenthesis is an optional list of argument names. The values of the arguments supplied during invocation are passed to these parameter names, which function as variables inside the method body.

Return Value: Every method yields a value. A return value is returned if a return keyword is used explicitly. In the event that it is not, the return value is automatically the value of the final expression evaluated in the method body.

Example of Simple Method Definition

In this example, a method is defined and invoked, and a parameter is explicitly defined by the method:

# my_first_method.rb
def my_function( a )
  puts "Hello, #{a}"
  return a.length
end

len = my_function( "Giraffe" )
puts "My secret word is #{len} long"

Output

Hello, Giraffe
My secret word is 7 long

Here, the return value of a.length is given to len.

An additional illustration of the use of parameters:

def hello(name)
  "Hello, #{name}"
end

puts hello("World")
puts hello("All")

Output

Hello, World
Hello, All

You can also read What Is Mean By Ranges In Ruby With Practical Code Examples

Invoking Methods

A method invocation expression needs the method name, zero or more arguments, and the object (the receiver) that the method is to be invoked on.

Implicit Receiver ()

The method is implicitly invoked on self if the receiver object is not explicitly specified. For example, puts and other global methods are implicitly called on self.

Optional Parentheses

Parentheses surrounding parameters are typically optional in Ruby when calling methods. Ruby code that uses the parentheses-optional syntax is frequently shorter and more widely used:

puts "Hello World"  # Looks like a keyword, but is a method call
puts("Hello World") # Equivalent method call

Output

Hello World
Hello World

Methods That Look Like Variables (Accessors)

A variable reference appears to be a method that is called without brackets and does not expect any arguments. We refer to these as attribute accessor methods, often known as getters.

Greetings, for instance.length does not access a field or variable with the same name; rather, it invokes a method. This is an excellent example of Ruby’s pure OO model, in which objects only reveal methods to the outside world.

Special Method Naming Conventions

Method names can express meaning by using trailing punctuation characters:

Question Mark (?): used to indicate predicates, which are methods that yield a true or false Boolean value. Examples include instance_of? and empty?

Exclamation Point (!): used to signal that care must be used, frequently to differentiate between a variant that returns a modified copy and a method that changes the object in place (mutator method). Sort versus sort! is one example.

Equals Sign (=): Methods that finish in = are attribute setter methods. You can use the syntax of assignment expressions to invoke these. The method o.x=(1) is used, for instance, when o.x = 1.

You can also read What Is Mean By Operators In Ruby, It’s Types With Examples

Method Types and Roles

Instance Methods

The most popular kind of methods are those that work with the state of a particular object (instance).

class Thing
  def somemethod
    puts "something"
  end
end

foo = Thing.new # create an instance of the class
foo.somemethod # => something

Output

something

The code above shows how to invoke an instance method on an object called foo.

Class Methods

These methods, which resemble static methods in other languages, are called on the class itself rather than an instance of that class. They are identified by putting the method name before the class name or self, followed by a period.

class Thing
  def Thing.hello(name) # Defined using class name
    puts "Hello, #{name}!"
  end
  
  def self.goodbye(name) # Defined using self
    puts "Goodbye, #{name}!"
  end
end

# Call the class methods to get output
Thing.hello("World")
Thing.goodbye("All")

Output

Hello, World!
Goodbye, All!

On the class, you would call these methods directly: Thing.hello(“World”).

You can also read Conditional Statements In Ruby: A Control Flow Techniques

Methods that Accept Blocks (Iterators)

Iterators and generators are programming constructs that take a block of code and run it, usually several times. The core of Ruby’s control flow approach is this. The method passes control (and optionally data) to the block using the yield keyword.

Custom Iterator Example:

With yield, you may create a method that takes a block and runs it:

def simple(arg1, arg2)
  puts "First we are here:  #{arg1}"
  yield
  puts "Finally we are here:  #{arg2}"
  yield
end

simple('start', 'end') { puts "Now we are inside the block" }

Output

First we are here:  start
Now we are inside the block
Finally we are here:  end
Now we are inside the block

Every time yield is encountered, the code inside the block (contained in {}) is performed. This block is linked to the method call.

Iterators with Arguments (yield):

Values can be sent from the yield statement to the block, which records them in parameters denoted by vertical bars (|…|).

def countdown(num)
  num.times do |i|
    yield(num-i) # Passes the current value to the block
  end
end

countdown(3) { |i| puts "Call number #{i}" }

Output

Call number 3
Call number 2
Call number 1

Advanced Method Concepts

Access Control

In Ruby, the functions public, private, and protected are used to regulate access to methods. They can be used with arguments (symbols of method names) to adjust visibility for particular, pre-defined methods, or without arguments to specify the default visibility for methods that are later specified.

Public: Anybody can get to it. This is the visibility by default.

Protected: can only be called by objects that belong to the defining class and its subclasses.

Private: Only in “functional form”—that is, without an explicit receiver object, meaning it is called implicitly on self—can it be called.

class Example
  def method_a # Public (default)
    puts "This is a public method."
  end

  private # All subsequent methods are private

  def method_p
    puts "This is a private method."
  end

  protected
  
  def method_k
    puts "This is a protected method."
  end
end

# To get an output, you must create an instance of the class
# and call a public method.
example = Example.new

# Call the public method. This will produce an output.
example.method_a

Output

This is a public method.

You can also read What Are The Loops In Ruby With Practical Code Examples

Dynamic Method Invocation

As an instance method of the Object class, the send method allows you to dynamically activate a method.

class Hello
  def hello(arg1, arg2)
    puts "Hello #{arg1} #{arg2}"
  end
end

h = Hello.new
h.send :hello, 'gentle', 'readers'

Output

Hello gentle readers

The message (the name of the method, ideally a symbol) is sent first, and the other arguments are delivered to that method.

Handling Undefined Methods ()

When an object receives a method call that it is unable to handle, Ruby calls the method_missing method. Programmers can implement forwarders, proxies, or domain-specific languages (DSLs) by overriding method_missing.

Example using method_missing:

class Animal
  def method_missing(method, *args, &block)
    puts "Cannot call #{method} on Animal"
  end
end

# Create a new instance (object) of the Animal class
animal = Animal.new

# Call the say_moo method on the new object
animal.say_moo

Output

Cannot call say_moo on Animal

You can also read What Is Mean By Iterators In Ruby And Types Of Iterators

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index