Return 初始化方法的值

Return value of initialize method

谁比我更精通 ruby 请回答为什么以下 returns 什么都没有?

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

puts 测试的结果不应该和我直接在 class 中调用 @total 上的 puts 一样吗?

它正常工作:

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

意思是,您在 initialize 中定义了实例变量 @total,并且您已经将它放在那里了。

should or should not "puts test" return the 33165

NO. 如果你想显示 @total,你可以定义一个 attr_reader :total 并按如下方式使用它:

test.total
#=> 33165

另一个选项(如果出于某种原因您不想定义 reader):

test.instance_variable_get :@total
#=> 33165

这就是您调用 new

时大致发生的情况
def new
  allocate object
  call initialize method on object
  return object
end

这就是为什么您不能 return @total 而是获取对象本身的原因。

Initialize 是从 Class#new 调用的,它 return 是新对象,而不是 #initialize 的(忽略的)return 值。