Ruby - Constructors: new and initialize

Introduction

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

Demo

class Thing 
    def set_name( aName ) 
        @name = aName # from   ww  w .j  av a  2s.c om
    end 
                         
    def get_name 
        return @name 
    end 
end 


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

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

t1 = Product.new("Sword", "a real thing") 
t2 = Product.new("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}"

Result

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