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 activity on this post. Initialize is called from Class#new and it returns the new object, not the (ignored) return value of #initialize. Show activity on this post.
Sometimes you have something more complicated though: Sometimes you will want a separate Initialize method because you want to call it at a separate time from construction. Sometimes you want one because you are writing multiple constructors, and you want to share some of the implementation between them.
Initializes the Workbook's data model. This is called by default the first time the model is used. expression. Initialize expression A variable that represents a Model object.
People do whatever is the easiest to read and understand, whatever requires the least extra code to be written, and whatever causes the least duplication of code. However, if you're making the Initialize method public, and not calling it from the constructor, I highly recommend you call it Initialize.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With