Статические члены Ruby

Опубликовано: 1 Февраля, 2022

В программировании статические ключевые слова в основном используются для управления памятью. Ключевое слово static используется для совместного использования одного и того же метода или переменной класса между объектами этого класса.

В Ruby есть различные члены класса. После создания объекта в Ruby методы и переменные для этого объекта находятся внутри объекта этого класса. Методы могут быть общедоступными, частными или защищенными, но в Ruby нет понятия статического метода или переменной. В Ruby нет ключевого слова static, которое обозначает, что конкретный метод принадлежит к уровню класса. Однако статическая переменная может быть реализована в ruby с использованием переменной класса, а статический метод может быть реализован в ruby с использованием переменной класса в одном из методов этого класса.

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

  • Static Variable
  • Static Method

Static Variable: A Class can have variables that are common to all instances of the class. Such variables are called static variables.A static variable is implemented in ruby using class variable. When a variable is declared as static, space for it gets allocated for the lifetime of the program. The name of the class variable always begins with the @@ symbol.
Example :

# Ruby program to demonstrate Static Variable
   
class Geeks
  
    # class variable
    @@geek_count = 0
  
    def initialize
        @@geek_count += 1
        puts "Number of Geeks = #{@@geek_count}"
    end
end
  
# creating objects of class Geeks 
g1 = Geeks.new
g2 = Geeks.new
g3 = Geeks.new
g4 = Geeks.new

Output:

Number of Geeks = 1
Number of Geeks = 2
Number of Geeks = 3
Number of Geeks = 4

In the above program, the Geeks class has a class variable geek_count. This geek_count variable can be shared among all the objects of class Geeks. the static variables are shared by the objects

Static Method: A Class can have a method that is common to all instances of the class. Such methods are called static methods.Static methods can be implemented in ruby using class variables in the methods of that class.
Example :

# Ruby program to demonstrate Static Method
  
class Geeks
      
    #class method
    @@geek_count = 0
  
    # defining instance method 
    def incrementGeek
        @@geek_count += 1
    end
    # defining class method
    def self.getCount
        return @@geek_count
    end
end
  
# creating objects of class Geeks
g1 = Geeks.new
# calling instance method
g1.incrementGeek()
  
g2 = Geeks.new
# calling instance method
g2.incrementGeek()
  
g3 = Geeks.new
# calling instance method
g3.incrementGeek()
  
g4 = Geeks.new
# calling instance method
g4.incrementGeek()
  
# calling class method
puts "Total Number of Geeks = #{Geeks.getCount()}"

Output:

Total Number of Geeks = 4

In the above program, incrementGeek() method is the static method of the class Geeks which can be shared among all the objects of class Geeks. Static member functions are allowed to access only the static data members or other static member functions, they can not access the non-static data members or member functions.