Table of contents
1.
Introduction
2.
Overview of the Ruby Method
2.1.
Syntax
3.
Suffixes in Method Names
3.1.
Exclamation Mark (!)
3.2.
Question Mark (?)
3.3.
Equals Sign (=)
4.
Prefixes in Variable Names
4.1.
Dollar symbol ($)
4.2.
At the rate symbol (@)
4.3.
Double at the rate (@@)
5.
Frequently Asked Questions
5.1.
Do you need to initialise variables in Ruby?
5.2.
What is class self in Ruby?
5.3.
What is the use of load and required in Ruby?
5.4.
What is the singleton method in Ruby?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Suffixes and Prefixes in Ruby

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello and welcome, readers! We hope you are doing well.  

Today, we will discuss the suffixes and prefixes in Ruby. Ruby uses suffixes and prefixes in method names to make code more readable. After completing this article, you will clearly understand the suffixes and prefixes in Ruby. So follow the article till the end. 

So, without further ado, let’s jump into the article.

Overview of the Ruby Method

In Ruby, a method is a collection of expressions that return a value. Methods allow you to break down your code into subroutines that can be called from anywhere in your program. Some programming languages refer to this as a function. A method can be defined as part of a class or on its own.

Method definition and method invocation: In Ruby, the method is defined with the help of the def keyword followed by method_name and ended with the end keyword. A method must be defined before being called, and the method's name should be in lowercase. Methods are called by their names. You can write the name of the method whenever you call a method. 

Syntax

#comment- syntax for method definition in ruby
def method_name(arg1, arg2, arg3)
 #put your code in here
end
#comment- syntax for method invocation in ruby
method_name(arg1, arg2, arg3)

Suffixes in Method Names

Suffixes are nothing but a part of a method's name. To make code more readable, Ruby uses suffixes in method names. There are only a few suffixes available. Conventions are the rules that govern which suffixes to use and when to use them. Using the define_method and send methods, we can work around the rules for creating suffixes. Let's discuss this in detail in the below sections.

To make it more clear, let's understand through the below example.

Example:

#suffixes in method names in ruby
#put your code in here
class Classroom
    TOTALSTUDENTS = 5
    def total_students
        "Total students in the class: #{@students}"
    end

    #getter method
    def students
        @students
    end

    #setter method
    def students=(students)
        @students = students
    end

    #rearrange students in the class
    def rearrange!
        @students.shuffle!
    end

    #check if student classroom is full
    def is_full?
        @students.length == TOTALSTUDENTS
    end
end

#create a new classroom
classroom = Classroom.new
classroom.students = ["John", "Jane", "Joe", "Jack", "Jill"]
puts classroom.total_students
puts classroom.students
puts "is_full?"
puts classroom.is_full?
classroom.rearrange!
puts "Rearrange! called:"
puts classroom.students
puts "----------------------------------------------------"
classroom.students = ["John", "Joe"]
puts classroom.students
puts "is_full?"
puts classroom.is_full?
puts classroom.total_students

Output:

Total students in the class: [“John”, “Jane”, “Joe”, “Jack”, “Jill”]
John
Jane
Joe 
Jack
Jill
is_full?
true
Rearrange! Called:
Joe
Jill
Jack
John
Jane
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
John 
Joe
is_full?
false
Total students in the class: [“John”, “Joe”]

The "is_full?" method we have used here gives a boolean value. The boolean value, as usual, may be true or false. Here it is used to answer the question of the classroom is full. The “rearrange!” method we have used here is to change the value of the instance variable @student so that the students' list will be in shuffled order. 

In the following sections, we will discuss different punctuation marks as suffixes in method names.

Exclamation Mark (!)

It modifies the state of a class instance. In simple terms, the exclamation mark indicates that the method can change the state of a class instance.

Question Mark (?)

The method with the question mark always answers a question. Generally, it returns a boolean value, which can be either true or false. In simple words, the question mark at the end of the method name indicates that this method is a query method, which usually returns a boolean value.

Equals Sign (=)

The equals sign indicates that the method assigns a value. More specifically, this suffix denotes that we can give a value to a class instance using this method.

Note: The method that does not have a suffix displays a help message about the current state of the class.

Prefixes in Variable Names

In addition to these punctuation characters at the end of method names, you'll notice punctuation characters at the start of Ruby variable names:

  • Global variables are prefixed with $.
  • Instance variables are prefixed with @.
  • Class variables are prefixed with @@.

Example:

#prefixes in ruby
class Classroom
  def initialize(teacher, students)
    @teacher = teacher
    @students = students
  end
end

puts Classroom.new("Mr. Teacher", ["John", "Jane"])
puts "Use of @@ prefix for class_variable"
puts "-----------------------"
#using @@ prefix for class variables
class Classroom
  @@teacher = "Mr. Smith"
  @@students = ["John", "Jane", "Bob"]
    def initialize(teacher, students)
        @teacher = teacher
        @students = students
        end
    def self.teacher
        @@teacher
        end
    def self.students
        @@students
        end
    puts "The teacher is #{@@teacher} and the students are #{@@students}"
end

puts "Use of @ prefix for instance variables"
puts "-----------------------"
#using @ prefix for instance variables
class Classroom
  @teacher = "Mr. Smith"
  @students = ["John", "Jane", "Bob"]
    def initialize(teacher, students)
        @teacher = teacher
        @students = students
        end
    def self.teacher
        @teacher
        end
    def self.students
        @students
        end
    puts Classroom.teacher
    puts Classroom.students
end

puts "Use of $ prefix for global variables"
puts "-----------------------"
#using $ prefix for global variable
$teacher = "Mr. Teacher"
$students = ["John", "Jane", "Bob"]
def initialize(teacher, students)
    @teacher = teacher
    @students = students
end
puts $teacher
puts $students

Output:

Use of @@ prefix for class_variable
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
The teacher is Mr. Smith and the students are [“John”, “Jane”, “Bob”]
Use of @ prefix for instance variable
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Mr. Smith
John
Jane
Bob
Use of $ prefix for global variables
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Main.rb:53: warning: redefining Object# initialise may cause infinite loop 
Mr. Teacher
John 
Jane
Bob

Dollar symbol ($)

A global variable is truly global if it's prefixed with $, crossing all boundaries, whether inside a class, method, module, or loaded source file. Some exceptions exist for built-in globals ($_ and $~). Using the $ symbol for global variables eliminates the need for declarators.

At the rate symbol (@)

A single @ is used as the prefix for an instance variable. In Python, using @myattribute replaces using self.myattribute. The instance variable can be created and used from within the instance itself by its very nature (actually, Ruby also supports the self-notation). You must use an accessor method to get or set the value from outside the instance refer to any Ruby reference for a discussion of attr_accessor. Using @, for instance, fast lookups and variables facilitate hiding and exclusion from dot notation.

Double at the rate (@@)

Instances of a class and its subclasses are the only ones that can share the @@-prefixed class variable. Constants are associated with a class or module namespace and the:: scope operator, and they begin with an uppercase letter (without a prefix).

Frequently Asked Questions

Do you need to initialise variables in Ruby?

Class variables begin with @@ and must be initialised before using in-method definitions.

What is class self in Ruby?

Self is a unique variable that identifies the object that "owns" the code currently running. Ruby frequently employs self. It is a particular variable that points to the object that "owns" the currently executing code.

What is the use of load and required in Ruby?

Adding new code to existing code in Ruby is done using the load and required functions. It is advised to use "load" whenever loading the code is necessary, such as each time the code is changed or a user accesses the URL. It is advised to use "require" in the case of autoloading.

What is the singleton method in Ruby?

A singleton method is applied to a single object. Singleton methods are frequently used for GUI elements where different actions must be taken when other buttons are pressed. Singleton methods aren't just for Ruby; they're also found in CLOS, Dylan, and other programming languages.

Conclusion

In this article, we have extensively discussed different suffixes and prefixes used in Ruby and their implementation. This article covered the suffixes used with methods and different prefixes used with variables to determine their scope.

We hope this blog has helped you enhance your knowledge of suffixes and prefixes in Ruby. To learn more, check out our articles on eight reasons why Ruby should be your first language, Everything you should know about ruby. Do upvote our blog to help other ninjas grow.

Check out this problem - Longest Common Prefix

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations and much more!

Happy Reading!

Live masterclass