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的结果相同吗?
这是你打电话时大致发生的事情 new
def new
allocate object
call initialize method on object
return object
end
Run Code Online (Sandbox Code Playgroud)
这就是为什么你不能返回@total而是获取对象本身的原因.
它工作正常:
test = ThreeAndFive.new(1,1000)
#=> #<ThreeAndFive:0x007ff54c5ff610 @total=33165>
Run Code Online (Sandbox Code Playgroud)
意思是,您在其中定义了实例变量@total,initialize并且在那里拥有它。
应该或不应该“放置测试”返回 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)
| 归档时间: |
|
| 查看次数: |
4400 次 |
| 最近记录: |