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

EXAMPLE

  1. Class person
  2. @@count = 0
  3. def initialize
  4. @@count + =1
  5. End
  6. def self.get_count
  7. @@count
  8. End
  9. End
  10. P1 =person.new If we use only p1
  11. P2 =person.new means the output is 1.
  12. Puts person.get_count

Output

CLASS CONSTANTS

Example

  1. Class calc
  2. PI = 3.14
  3. End
You can access constants using the class name, followed by two colon symbols (::) and the constant name. For example -

Example

  1. Puts calc :: PI

Output

3.14

THE TO_S METHOD

Example

  1. Class person
  2. # some code
  3. End
  4. P = person.new
  5. Puts P

Output

#<person:0x0000000271e128>

Example

  1. Class person
  2. def initialize(n,a)
  3. @name = n
  4. @age = a
  5. End
  6. def to_s
  7. #{@name} is # {@age} years old.
  8. End
  9. End
  10. P = person.new(“David”, 28)
  11. Puts P

Output

David is 28 years old.

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.