2

我觉得这很奇怪。为什么我不能这样做?:

puts Time.now
x=2
puts x
puts x.class
sleep x
puts Time.now
x=x.seconds
puts x
puts x.class
sleep (x)
puts Time.now

我得到的输出是:

Mon Oct 01 16:14:58 +0530 2012
2
Fixnum
Mon Oct 01 16:15:00 +0530 2012
2
Fixnum
rake aborted!
can't convert ActiveSupport::Duration into time interval
/Users/hariharanganapathiraman/Documents/MigrationScripts/sample/lib/import/boot.rb:23:in `sleep'

同样,它不适用于.minutesor .days

4

2 回答 2

5

那是因为ActiveSupport::Duration模仿自己作为Fixnum类:

ActiveSupport::Duration.new(3600, [[:seconds, 3600]]).class #=> Fixnum

使用sleep(2.seconds.to_i).

于 2012-10-01T11:10:12.480 回答
3

The problem is with ActiveSupport::Duration It's inherited from BasicObject that have only limited number of methods and does not have class method. If you take a look in ActiveSupport::Duration implementation you'll see that all methods are proxied(via method_missing) to @value, that's Fixnum in your case.

Hence, since ActiveSupport::Duration has no class method, your class call for a x.seconds goes to Fixnum.

于 2012-10-01T11:28:51.787 回答