Static Members in Ruby Programming


Static Members in Ruby are declared with the help of the class. Since Ruby doesn't provide a reserved keyword such as static, when we make use of the class variable, then we create a static variable and then we can declare a method of that class in which the static variable is defined as a static method as well.

In Ruby, there are two implementations for the static keyword −

  • Static variable

  • Static method

In this article, we will explore both these implementations where first, we will explore a code example of how to declare a static variable and then we will see how to declare a static method.

Static variable

To declare a static variable, we just need to declare a class variable that will act as a static one, as it will be common to all the instances of the class. In simple terms, when we talk about Ruby, the static variables are declared using the class variable.

When we declare a variable as static, the space for it is allocated for the entire lifetime of the program.

It should be noted that the name of the static variable always begins with the @@ symbol.

Example 1

Consider the code shown below, where we are declaring a static variable.

class Coders
   # static class variable
   @@coders_count = 0
   def initialize
      @@coders_count += 1
      puts "Number of Coders = #{@@coders_count}"
   end
end

# creating objects of class Coders
a = Coders.new
b = Coders.new
c = Coders.new
d = Coders.new
e = Coders.new

Output

It will produce the following output −

Number of Coders = 1
Number of Coders = 2
Number of Coders = 3
Number of Coders = 4
Number of Coders = 5

In the above code, we have a class named Coders in which there's a class variable named coder_count. This coder_count variable can be shared among all the objects that we will create of the class Coders, hence acting as a static variable.

Static Method

When we define a method in a class that is common to all instances of the class, we can call it a static method.

Example 2

Consider the code shown below

class Coders
   @@coders_count = 0

   def incrementCoder
      @@coders_count += 1
   end

   def self.getCount
      return @@coders_count
   end
end

# creating objects of class Coders
a = Coders.new
a.incrementCoder()

b = Coders.new
b.incrementCoder()

c = Coders.new
c.incrementCoder()

# calling class method
puts "Total Number of Coders = #{Coders.getCount()}"

Output

It will generate the following output −

Total Number of Coders are = 3

Updated on: 25-Jan-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements