Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • The initialize method in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 35
    Comment on it

    This method is like a constructor of other object oriented programming languages.
    when you want to initialize some class variables while creating an object, we use this method.
    . like any other ruby method,it starts with def keyword

    class abc
       def initialize(w,h)
          @width, @height = w, h
       end
    end 
    

    Example

    class Evon
       # constructor method
       def initialize(w,h)
          @width, @height = w, h
       end
    
       # accessor methods
       def printWidth
          @width
       end
    
       def printHeight
          @height
       end
    end
    
    # create an object
    b = Evon.new(35, 45)
    
    # use accessor methods
    x = b.printWidth()
    y = b.printHeight()
    
    puts "Width of the box is : #{x}"
    puts "Height of the box is : #{y}"
    

 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: