initialize方法的返回值

The*_*ley 5 ruby class return-value

有人可能比我更精通红宝石请回答为什么以下什么都不返回?

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
Run Code Online (Sandbox Code Playgroud)

不应该把puts测试的结果与我在类中直接调用了@total的结果相同吗?

roh*_*t89 9

这是你打电话时大致发生的事情 new

def new
  allocate object
  call initialize method on object
  return object
end
Run Code Online (Sandbox Code Playgroud)

这就是为什么你不能返回@total而是获取对象本身的原因.

  • 为什么要“大致”?为什么不准确地拼写出会发生什么呢?def initialize(* args,&block)object =分配; object.send(:initialize,* args,&block); 返回对象 结束` (2认同)

Dig*_*oss 8

Initialize 被调用Class#new并返回新对象,而不是#initialize.


And*_*eko 5

它工作正常:

test = ThreeAndFive.new(1,1000)
#=> #<ThreeAndFive:0x007ff54c5ff610 @total=33165>
Run Code Online (Sandbox Code Playgroud)

意思是,您在其中定义了实例变量@totalinitialize并且在那里拥有它。

应该或不应该“放置测试”返回 33165

不。如果你想@total被显示,你可以定义 anattr_reader :total 并按如下方式使用它:

test.total
#=> 33165
Run Code Online (Sandbox Code Playgroud)

另一种选择(如果由于某种原因您不想定义阅读器):

test.instance_variable_get :@total
#=> 33165
Run Code Online (Sandbox Code Playgroud)