Ruby - Constructors: new and initialize


The following code shows how to add constructor to a class.


class Thing 
    def set_name( aName ) 
        @name = aName # from  ww  w. ja v a 2s .c  o m
    def get_name 
        return @name 

class Product 
      def initialize( aName, aDescription ) 
          @name           = aName 
          @description  = aDescription 
      def to_s # override default to_s method 
       "The #{@name} Product is #{@description}\n" 

thing1 = 
thing1.set_name( "A lovely Thing" ) 
puts thing1.get_name 

t1 ="Sword", "a real thing") 
t2 ="Ring", "a gift") 
puts t1.to_s 
puts t2.to_s 
# The inspect method lets you look inside an object 
puts "Inspecting 1st Product: #{t1.inspect}"


Product class contains a method named initialize, which takes two arguments.

Those two values are assigned to the @name and @description variables.

When a class contains a method named initialize, it will be called automatically when an object is created using the new method.

It a convenient place to set the values of an object's instance variables.

A method called to_s returns a string representation of a Product object.

The method name, to_s, is not arbitrary.

The same method name is used throughout the standard Ruby object hierarchy.

The to_s method is defined for the Object class itself, which is the ultimate ancestor of all other classes in Ruby.

By redefining the to_s method, we returns more appropriate to the Product class than the default method.

In other words, we have overridden its to_s method.

Related Topics