Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of initialize method [duplicate]

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?

like image 374
TheRealMrCrowley Avatar asked Oct 07 '16 20:10

TheRealMrCrowley


People also ask

What is the difference between initialize and initialize return value?

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.

Why would you want a separate Initialize method?

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.

What does initialize mean in Excel?

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.

Should I call Initialize () method from constructor or constructor?

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.


1 Answers

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.

like image 198
rohit89 Avatar answered Sep 28 '22 09:09

rohit89