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
    • 197
    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

    1. class abc
    2. def initialize(w,h)
    3. @width, @height = w, h
    4. end
    5. end

    Example

    1. class Evon
    2. # constructor method
    3. def initialize(w,h)
    4. @width, @height = w, h
    5. end
    6.  
    7. # accessor methods
    8. def printWidth
    9. @width
    10. end
    11.  
    12. def printHeight
    13. @height
    14. end
    15. end
    16.  
    17. # create an object
    18. b = Evon.new(35, 45)
    19.  
    20. # use accessor methods
    21. x = b.printWidth()
    22. y = b.printHeight()
    23.  
    24. puts "Width of the box is : #{x}"
    25. puts "Height of the box is : #{y}"

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: