Ruby | Class Method and Variables

11 Nov, 2019
Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.Syntax 1:
def class_method_name
  # some code
end
Here, we can access the above method only with the help of an object.Syntax 2:
def class_name.class_method_name or self.class_method_name
  # some code
end
Here, we can access the above method there is no need to create objects of the Class as we can directly access it.Here, the self keyword refers to the entire class itself, not to an instance of the class. In this case, we are inside the class only, not inside an instance method of that class. So, we are in the class scope.
Class Variables are the variables that are defined inside the class, where only the class method has access to. Class Variables starts with @@ and must be initialized first then they can be used in method definitions.Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module within which the class variables are defined.When a class variables is override it will produce warnings with the -w option.
Syntax:
@@variable_name = value
What is the use of class variables and methods?
Let’s say for suppose we want to keep a count of how many grocery items you have added to your shopping items, for that, we need a variable apart from instance variable as instance variable appears unique for every object created and by using a global variable it can be easily manipulated from anywhere from the program.
So, for we use a class variable and with the help of a class method we can keep track of the total number of grocery items got listed and in many various other ways.
Below is the example:
# Program in Ruby for a count of total Grocery itemsclass Grocery  # class variable@@total_count = 0  # class array@@items_list = []  def add_item(item)      # adding item to the array    @@items_list.push(item)    @@total_count += 1#countingend  def print_items    puts "Total number of items --> #@@total_count";    puts "All items --> #@@items_list";end# direct accessdef Grocery.printitems_only# or self.printitems_only    puts "\nGrocery.printitems_only", @@items_list.join("\n");endend  list = Grocery.new()  list.add_item("shampoo")list.add_item("face wash")list.add_item("serum")list.add_item("mud pack")list.add_item("tea tree oil")list.add_item("toner")  list.print_items  # direct accessGrocery.printitems_only  # throws an errorlist.printitems_only
Output
Total number of items --> 6
All items --> ["shampoo", "face wash", "serum", "mud pack", "tea tree oil", "toner"]

Grocery.printitems_only
shampoo
face wash
serum
mud pack
tea tree oil
toner
main.rb:35:in `': undefined method `printitems_only' for # (NoMethodError)
Did you mean?  print_items

Here we are using the @@total_count class variable, inside of our #add_item(item) method, which is an instance method. when a new item is added, the method accesses the @@total_count class variable and increment its value by 1. And, we are using the @@items_list class array, inside of our #add_item(item) method, which is an instance method. when a new item is added, the method accesses the @@items_list class array and adds the item name to the array. We can access the class variables anywhere in the class in both class and instance methods. And if we use either self.printitems_only or Grocery.printitems_only they execute the same but while accessing we can only access by class name as self represents the class only inside the class.
Picked
Ruby class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Ruby | Case Statement
Ruby | Hash delete() function
Ruby | unless Statement and unless Modifier
Ruby | Data Types
Ruby | String capitalize() Method