INTRODUCTION
Today, we are going to see the class methods, variables, and the to_s method in Ruby programming language. The brief description of this concept is given below.
CONTENTS
- Class Variables.
- Class Constants.
- The to_s method.
CLASS VARIABLES
- Class variables are accessible to every object of a class.
- A class variable belongs to the class, not the object.
- You declare a class variable using two @signs for example, @@name.
- We can, for example, keep count of all person objects created using a class variable.
EXAMPLE
- Class person
- @@count = 0
- def initialize
- @@count + =1
- End
- def self.get_count
- @@count
- End
- End
- P1 =person.new If we use only p1
- P2 =person.new means the output is 1.
- Puts person.get_count
Output
- In the code above, @@count is a class variable.
- Since the initialize method is called for every object that is created, incrementing the @@count variable will keep track of the number of objects created.
- We also defined a class method called get_count to return the value of the class variable.
- In the code above, we have created two objects of the person so the value of the @@count variable is 2.
- A class variable is usually used when you need information about the class, not the individual objects.
CLASS CONSTANTS
- A class can also contain constants.
- Remember, constant variables do not change their value and start with a capital letter.
- It is common to have uppercase names for constants.
Example
You can access constants using the class name, followed by two colon symbols (::) and the constant name. For example -
Example
Output
3.14
THE TO_S METHOD
- The to_s method comes built-in with all classes.
- It gets called when you output the object.
Example
- Class person
-
- End
- P = person.new
- Puts P
Output
#<person:0x0000000271e128>
- When we call puts p, Ruby automatically calls the to_s method for the object p, so puts p is the same as puts p.to_s.
- By default, the to_s method prints the object’s class and an encoding of the object id.
- We can define our own to_s method for a class and add custom implementation to it.
- For example, we can generate an informative, formatted output for our person class.
Example
- Class person
- def initialize(n,a)
- @name = n
- @age = a
- End
- def to_s
-
- End
- End
- P = person.new(“David”, 28)
- Puts P
Output
David is 28 years old.
- The to_s method also gets called when the object is used as a value in a string, like”#{P}”.
- Defining the to_s method makes it easier and shorter to output the information of an object in the format needed, as opposed to defining a custom method and calling it from an object.
- When you define the to_s method, you call puts on your object (puts obj) where with a custom method, you have to explicitly call it from the object (puts obj.info).
CONCLUSION
In this write-up, we learned some new concepts in Ruby. I hope it will help you gain more knowledge. In the future, we will go deeper into the concepts of Ruby programming.