Ruby | Class Method and Variables
Last Updated :
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:
class Grocery
@@total_count = 0
@@items_list = []
def add_item(item)
@@items_list.push(item)
@@total_count += 1
end
def print_items
puts "Total number of items --> #@@total_count";
puts "All items --> #@@items_list";
end
def Grocery.printitems_only
puts "\nGrocery.printitems_only", @@items_list.join("\n");
end
end
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
Grocery.printitems_only
list.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.
Similar Reads
Ruby | Hash values_at method
Hash#values_at() is a Hash class method which returns the array containing the values corresponding to keys. Syntax: Hash.values_at() Parameter: Hash values_at Return: array containing the values corresponding to keys. Example #1 : # Ruby code for Hash.values_at() method # declaring Hash value a = {
1 min read
Ruby | Hash value? method
Hash#value?() is a Hash class method which checks whether the argumented 'value' is present in the array or not. Syntax: Hash.value?()Parameter: Hash value?Return: true - if argumented 'value' is present in the array otherwise return false Example #1 : C/C++ Code # Ruby code for Hash.value?() method
2 min read
Instance Variables in Ruby
There are four different types of variables in Ruby- Local variables, Instance variables, Class variables and Global variables. An instance variable in ruby has a name starting with @ symbol, and its content is restricted to whatever the object itself refers to. Two separate objects, even though the
3 min read
Ruby getters and setters Method
In a Ruby class we may want to expose the instance variables (the variables that are defined prefixed by @ symbol) to other classes for encapsulation. Then, in that case, we use the getter and setter methods. these methods allow us to access a class's instance variable from outside the class. Getter
5 min read
Ruby | Hash size() method
Hash#size() is a Hash class method which returns the count of key-value pair in the hash. Syntax: Hash.size() Parameter: Hash values Return: count of key-value pair in the hash. Example #1 : # Ruby code for Hash.size() method # declaring Hash value a = {a:100, b:200} # declaring Hash value b = {a:10
1 min read
Ruby | String chars() Method
chars is a String class method in Ruby which is used to return an array of characters in str. Syntax: str.chars Parameters: Here, str is the given string Returns: An array of the characters. Example 1: # Ruby program to demonstrate # the chars method # Taking a string and # using the method puts
1 min read
Ruby| String Clear Method
clear is a String class method in Ruby which is used to make the string empty. Syntax: str.clear Parameters: Here, str is the given string. Return : An empty string. Example 1: # Ruby program to demonstrate # the clear method # Taking a string and # using the method puts "String".clear put
1 min read
Method Visibility in Ruby
Method visibility in Ruby refers that instance methods can be public, private or protected. Methods are by default public unless they are explicitly declared private or protected. Method visibility is used in Ruby to achieve Data Abstraction i.e showing only required information and hiding the backg
3 min read
Ruby | Time <=> method
The is an inbuilt method in Ruby returns -1, 0, 1 depending on whether time is less than, equal to, or greater than other time. It is returns nil if two times are incomparable. Syntax: time <=> otherTime Parameters: The function accepts no parameter Return Value: It returns -1, 0, 1 depending
1 min read
Ruby | Set add() method
The add is an inbuilt method in Ruby which adds an element to the set. It returns itself after addition. Syntax: s1.name.add(object) Parameters: The function takes the object to be added to the set. Return Value: It adds the object to the set and returns self. Example 1: #Ruby program to illustrate
1 min read