Return value of initialize method

Question

Can someone more versed in ruby than I please answer why the following returns nothing?

class ThreeAndFive
  def initialize(low_number, high_number)
    @total = 0
    (low_number..high_number).each do |number|
      if (number % 3 == 0 && number % 5 == 0)
        @total += number
      end
    end
    #puts @total here returns value of 33165
    return @total
  end
end

test = ThreeAndFive.new(1,1000)
#This returns nothing but "#<ThreeAndFive:0x25d71f8>"
puts test

shouldn't the result of puts test be the same as if i had called puts on @total directly in the class?


Show source
| class   | ruby   | return-value   2016-10-07 22:10 3 Answers

Answers ( 3 )

  1. 2016-10-07 22:10

    It works correctly:

    test = ThreeAndFive.new(1,1000)
    #=> #<ThreeAndFive:0x007ff54c5ff610 @total=33165>
    

    Meaning, that you defined instance variable @total in initialize and you have it there.

    should or should not "puts test" return the 33165

    NO. If you wanted to have @total to be displayed, you would define an attr_reader :total and used it as follows:

    test.total
    #=> 33165
    

    Another option (if for some reason you did not want to define reader):

    test.instance_variable_get :@total
    #=> 33165
    
  2. 2016-10-07 22:10

    This is what roughly happens when you call new

    def new
      allocate object
      call initialize method on object
      return object
    end
    

    This is why you cannot return @total and are instead getting the object itself.

  3. 2016-10-07 22:10

    Initialize is called from Class#new and it returns the new object, not the (ignored) return value of #initialize.

◀ Go back