Return value of initialize method


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
    #puts @total here returns value of 33165
    return @total

test =,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 to Return value of initialize method ( 3 )

  1. 2016-10-07 22:10

    It works correctly:

    test =,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:
    #=> 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

    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.

Leave a reply to - Return value of initialize method

◀ Go back