Ruby Class

Class is like template which are provide certain rules to implement custom class.

Defining a custom Ruby Class

class keyword are used to define custom class followed by the name of class. within curly braces are define class methods and properties.

class Class_Name
  #class logic here
end

Defining Properties of class

Class Method : class method are two types in ruby programming. First one is basic and normal method. There can defined as follows.

class Demo
  #define methods
  def set_values(data1,data2)
    #method logic here
  end
  def get_values
    #method logic here
  end
end

This type of method will be accessible by the class instance objects. And second are class method this method are defined by class name (or self) and followed by dot and method name.

class Demo

  #class methods
  #define by class name
  def Demo.test_value(data1,data2)
    puts ("#{data1} , #{data2}")
  end

  #class method 
  #define by self
  def self.print_value
    #method logic here
    puts 10
  end
end

Demo.test_value 89 , 20
Demo.print_value
89 , 20
10

Class method are used by class name. In this method are not possible to access directly any class instance variable. But in case when we are need to use particular instance variable value of inside this function. In this situation we can pass instance object of class method as parameter. And using of instance_variable_get(:@var) use instance variable.

class Demo
  def set_data(data)
    @data = data
  end
  #class method 
  #define by self
  def self.print_value obj
    #get instance variable of obj
    puts obj.instance_variable_get(:@data)
  end
end

obj= Demo.new
obj.set_data 100
Demo.print_value obj
100

Instance variable : This type of variables will defined by @ symbols . When create dynamic objects of class using new keyword this instance variable are allocated to this created object. means each instance variables is part of instance object.

class MyBook

  def set_record(name,genre,language,isbn,pages,price)
    #instance variable of class
    @name = name
    @genre = genre
    @language = language
    @isbn = isbn
    @pages = pages
    @price = price
  end
  #Display value of instance variable
  def view_record
    puts("Name : #{@name}")
    puts("Genre : #{@genre}")
    puts("Language : #{@language}")
    puts("ISBN : #{@isbn}")
    puts("Pages : #{@pages}")
    puts("Price : #{@price} $")
  end
end
#Make class instance (objects)
ruby = MyBook.new
#set instance variable values
ruby.set_record "Java Programming","Computer","English","!00904389",200,100

ruby.view_record


novel = MyBook.new
#set instance variable values
novel.set_record "Novels","Fiction","English","!EBN09021",400,90

novel.view_record
Class Instance variables in ruby
Name : Java Programming
Genre : Computer
Language : English
ISBN : !00904389
Pages : 200
Price : 100 $
Name : Novels
Genre : Fiction
Language : English
ISBN : !EBN09021
Pages : 400
Price : 90 $

instance variable value are set by class method, constructor of class and using of class objects. But interesting that when after create objects of class using ClassName.new and after that not set instance variable values then in this situation that is contain nil value. Let see this example.

class Test
  @info = "Hi"
  
  def new_info(info)
    @info = info
  end

  def view_info
    puts @info
  end
end
#make object of class
obj=Test.new
obj.view_info #nil
obj.new_info("Hello")
obj.view_info #Hello

So after create instance of class there are set initial values. Note that in this example @info are define with initial value but when created new instance that are copying of this @info variable. And in this example we are not set any value then compiler is sets default value to this instance variable

Class Variables: Class variable are defined by @@ symbols. This type of variable are create only one copy and all object are share this class variables.

class Record
  #class variable
    @@class_data = 14
    def set_data(data)
      #instance variable
      @data=data
    end
    def values
      #display data of class and instance variables 
      puts @@class_data
      puts @data
    end
end
#make objects of class Record
ins1 = Record.new
ins1.set_data  50
ins2 = Record.new
ins2.set_data  100

ins1.values
ins2.values
Example of class variable in ruby
14
50
14
100

Creating objects of class

Variable which are hold the instance reference of class it's called object. Object is real world entities which are use class properties and method. Let's see an example to create three objects in class Employee.

class Employee

  #Method which is sets value of class instance variable 
  def set_data(name,type,salary)
    @name = name
    @type = type
    @salary = salary
  end

  #Display class instance variable values
  def about
    puts("name : #{@name}")
    puts("type : #{@type}")
    puts("salary : #{@salary}")
  end

end
#make object of Employee class
accountant = Employee.new
accountant.set_data "Jhon","Accountant",590242.5
accountant.about

driver = Employee.new
driver.set_data "Angelo","Driver",30000
driver.about

developer = Employee.new
developer.set_data "Wood","Driver",890000
developer.about
Make class objects in ruby
name : Jhon
type : Accountant
salary : 590242.5
name : Angelo
type : Driver
salary : 30000
name : Wood
type : Driver
salary : 890000

Clone object

Normally object are hold the reference of class instance. When we are assign one object to another object, In this situation both objects are work to same instance of class. And clone() method are used to clone particular objects of class.

class DataSet
  def initialize(first,last)
    @first_name=first
    @last_name=last
  end
  def setNew(first,last)
    @first_name=first
    @last_name=last
  end
  def display()
    puts "First Name : #{@first_name}"
    puts "Last Name  : #{@last_name}"
  end
end

first = DataSet.new("Simth","Wood")

second=first.clone() #clone objects
second.setNew("Ruby","Seed") #set new values

first.display
second.display
Clone objects in ruby
First Name : Simth
Last Name  : Wood
First Name : Ruby
Last Name  : Seed

Defining constructor

Constructor are used to set initialize values of class variable and instance variable. Constructor is defined in ruby programming by using of initialize() method. That is automatically invoked whenever new instance are create by class. There are syntax as follows.

def initialize(parameter_list)
  #set variable value here 
end

Lets see an example to define constructor

class Student
  #Class constructor
  def initialize(roll,name,section)
    #Assign values of instance variables
    @roll=roll
    @name=name
    @section=section
  end
  #Display values of instance variables
  def record
    puts "Id : #{@roll}"
    puts "Name : #{@name}"
    puts "Section : #{@section}"
  end
end
#Make objects of Student class
first = Student.new(1,"Smith","5'th B")
second = Student.new(7,"ruby","10'th A")

#Display objects values
first.record
second.record
Example Ruby Class Constructor
Id : 1
Name : Smith
Section : 5'th B
Id : 7
Name : ruby
Section : 10'th A

Ruby Inner Class

Nested class is a way to defining one class inside another class in Ruby. let see the syntax of defining inner class.

class Outer
  #Outer class methods here

  #Define Inner class
  class FirstInner
    #Define class methods and properties
    #Of inner class
  end

  #Define Inner class
  class SecondInner
    #Define class methods and properties
    #Of inner class
  end
end

When we defining inner classes, outer class holding the reference of inner class.. Outer class name and :: Scope resolution operation are used to create inner class objects.

class OuterClass
    def initialize(name)
        @name = name
    end

    def printData
        puts "Outer Class Name = #{@name}"
    end

    class InnerClass
        def initialize(status, info)
            @status = status
            @info = info
        end

        def infoData
            puts "Inner class Status = #{@status}"
            puts "Inner class Info   = #{@info}"
        end
    end
end

outer  = OuterClass.new("Ruby")
outer.printData()

#make objects of inner class
inner = OuterClass::InnerClass.new(true, "Inner Demo")
inner.infoData()
Inner class in ruby
Outer Class Name = Ruby
Inner class Status = true
Inner class Info   = Inner Demo

In this example created a inner class objects by using scope resolution operator. In other way if you are need to retrieve inner class properties with the help of outer class objects then we can do this way.

class OuterClass
    def initialize(name,status,info)
      #Create inner class objects
      #ref  is holding the instance reference
      @ref=InnerClass.new(status,info)  
        @name = name
    end

    def printData
        puts "Outer Class Name = #{@name}"
        @ref.infoData #execute inner class method
    end

    class InnerClass
        def initialize(status, info)
            @status = status
            @info = info
        end

        def infoData
          
            puts "Inner class Status = #{@status}"
            puts "Inner class Info   = #{@info}"
        end
    end
end

outer = OuterClass.new("Ruby",true, "Inner Demo")
outer.printData()
Use inner class properties
Outer Class Name = Ruby
Inner class Status = true
Inner class Info   = Inner Demo

In this example ref are hold the reference of inner class instance. similar way we can hold the reference of outer class inside a inner class variable and access properties of outer class.

class attr_accessor

attr_accessor are useful to get and set class instance variable value by objects. That is internally create method of class instance variable which are defined by attr_accessor. This created method are providing the information of instance. let me show you first what is the mean by this definition. Suppose assume that we are need to use class instance variable value to an object.

class Book
  def initialize(name)
    @name = name
  end
end
obj=Book.new("Ruby")
puts obj.name #error in this line
Instance variable

In this example everything is fine but last statement are try to retrieve instance variable values, then compiler are producing the following error.

test.rb:7:in `<main>': undefined method `name' for #<Book:0x00000001be01f8 @name="Ruby"> (NoMethodError)

In this example Book is a class and obj is object of this class @name is instance variable. That value are set by constructor of class. In this situation obj.name are try to access the value of instance then complier produce NoMethodError error.

We can solve this problem to define a custom method which are get and set the value of instance variable of class. See this example.

class Book
  def initialize(name)
    @name = name
  end
  #get instance varibale name value
  def name
    @name
  end

  #set method
  def name=(new_name)
    @name = new_name
  end
end
obj=Book.new("Ruby")
puts obj.name
obj.name="Ruby 2.0"
puts obj.name
Ruby
Ruby 2.0

That is basic way to solve this problem. But in case there are multiple instance variable of class so that is not good way to define each instance variable get and set methods. In this situation we can use attr_accessor to define instance variable. For example

class Book
  #That is implement two methods 
  #name method are implement to get @name values
  #name= method are implement to set new value to name  
  attr_accessor :name
  def initialize(name)
    @name = name
  end
end
obj=Book.new("Ruby")
puts obj.name #get method execute
obj.name="Ruby 2.0"
puts obj.name #set method execute
attr_accessor Example
Ruby
Ruby 2.0

class attr_reader

In above example attr_accessor are implement two variant of method (getting and setting method). attr_reader are used to create get() method of instance variable of class.

class Employee
  attr_reader :name,:salary
  def initialize(name,salary)
    @name=name
    @salary=salary
  end
end
driver = Employee.new("Lee",10002.4)

worker = Employee.new("Julie",50003)

#Get method work
puts driver.name
puts driver.salary

puts worker.name
puts worker.salary

# not define set method
# driver.salary = 120000

attr_reader Example
Lee
10002.4
Julie
50003

class attr_writer

defining instance variable by attr_writer. That is create setter() method to instance variable. Which can be update new value instance variable

class Employee
  attr_writer :name,:salary
  def initialize(name,salary)
    @name=name
    @salary=salary
  end
  def info()
   #custome method to display value
  puts @name
  puts @salary
  end
end
driver = Employee.new("Lee",10002.4)

worker = Employee.new("Julie",50003)

puts "Initial value"
driver.info
worker.info

puts "When update name"
driver.name="Kavin"
worker.name="Smith"
driver.info
worker.info
attr_writer Example
Initial value
Lee
10002.4
Julie
50003
When update name
Kavin
10002.4
Smith
50003

Method Visibility

In Ruby programming by default initialize and global method under the Object class are private. And other define normal methods are public. There are three type of protection level are available in ruby programming. Such as public, private and protected.

private

Private method of class is accessible by only itself class method. That is cannot be use outside of class or inherit class. Object of class are use public method and protected method of class and inside this method are possible to execute private method. So private method cannot execute by directly of class object. Let see an example.

class Demo
  #private method 
  private
  def method_two
    puts "Private method"
  end
  #When Here define other method of class is by default private, 
  #Because private label is defined of above
  #Otherwise define public and protected method. See in below

  #public methods of class
  public
  def method_one
    puts "Public method"
  end

  def method_three
    method_two #execute private method
  end
end
#make object
obj=Demo.new

#execute public method
obj.method_one
obj.method_three
Private method visibility in ruby
#Output
Public method
Private method

In this example define method_two() are private. This method are use within the public method method_three(). There are other way is possible to define private method.

class Demo
  def method_two
    puts "Private method"
  end
  def method_one
    puts "Public method"
  end

  def method_three
    method_two
  end
  #using named arguments
  #method_two is private
    private:method_two
end
#make object
obj=Demo.new

#execute public method
obj.method_one
obj.method_three
#Output
Public method
Private method

protected

Protected method are usable of within the class and inherited class method. They are directly cannot accessible by class objects.

class Demo
  
  def method_two
    puts "Protected method"
  end
  def method_one
    puts "Public method"
  end

  def method_three
    method_two
  end
  protected:method_two
end
#make object
obj=Demo.new

#execute public method
obj.method_one
obj.method_three
#Output
Public method
Protected method

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved