ActiveSupport TimeWithZone 如何保留值?

How ActiveSupport TimeWithZone retains values?

我试过类似的东西:

a = ActiveSupport::TimeWithZone.new(Time.now,Time.zone)
b = a
a - b  # it gives 0.0 (float)

而当我尝试时:

a.to_s  # it gives "2019-06-30 11:11:42 -0700"
a.to_a  # it gives [42, 11, 11, 30, 6, 2019, 0, 181, true, "PDT"]

那么这个浮点数是从哪里来的呢?

来自 Time class 的

Ruby 的 -(减法)方法用于此,正如您在 Rails source code for TimeWithZone 中看到的那样。

def -(other)
  if other.acts_like?(:time)
    to_time - other.to_time
  elsif duration_of_variable_length?(other)
    method_missing(:-, other)
  else
    result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
    result.in_time_zone(time_zone)
  end
end

根据 Ruby docs 它 returns 一个浮点数。

Difference — Returns a difference in seconds as a Float between time and other_time, or subtracts the given number of seconds in numeric from time.