Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Ruby Constructors and Setter and Getter

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 221
    Comment on it

    Ruby Constructors

    •  1. Ruby supports constructors.
    •  2. They are declared with the method initialize.
    •  3. Initialize method is called automatically when the object is created.

    Example:

    class Cons
        def initialize(name,email,password)
          @name=name
          @email=email
          @password=password
        end
      end
    • In this example we have provided the initialize method with three arguments i.e name , email and password.
    •   Then we created the instance variables and assigned them with the values of name ,email and password.
    •   The initialize method is called automatically when we create an object of Cons class i.e Cons.new.

    Setter And Getter Methods:

    These methods can be automatically created by using the attr_accessor method or can be created manually.

    Example:

    class Student
      attr_accessor :name , :percentage
    end
    
      stu = Student.new
    
      stu.percentage = 60%
      =>60%
    
      stu.name = "Rahul"
      =>"Rahul"
    
      puts stu.name , stu.percentage

    Output:
      Rahul
      60%

    We can also write this code by definig the setter and getter methods on our own.

    Example:

    class Student
        def name          #getter method
          @name
        end
    
        def name = (name)   #setter method
          @name = name
        end
    
        def age
          @percentage
        end
    
        def percentage = (percentage)
          @percentage
        end
    end

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: