TheRealMrCrowley TheRealMrCrowley - 20 days ago 5
Ruby Question

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?


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