Ruby,从Date.day_fraction_to_time获取小时,秒和时间

前端之家收集整理的这篇文章主要介绍了Ruby,从Date.day_fraction_to_time获取小时,秒和时间前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_0@
我发现这个方法 here.
start = DateTime.now
  sleep 15
  stop = DateTime.now
  #minutes
  puts ((stop-start) * 24 * 60).to_i

  hours,minutes,seconds,frac = Date.day_fraction_to_time(stop-start)

我有以下错误

`<main>': private method `day_fraction_to_time' called for Date:Class (NoMethodError)

我检查了/usr/lib/ruby/1.9.1/date.rb,我发现了它:

def day_fraction_to_time(fr) # :nodoc:
  ss,fr = fr.divmod(SECONDS_IN_DAY) # 4p
  h,ss = ss.divmod(3600)
  min,s  = ss.divmod(60)
  return h,min,s,fr * 86400
end

但如果我用ruby1.8运行它,我没有问题. /usr/lib/ruby/1.8/date.rb给了我:

def self.day_fraction_to_time(fr)
    ss,fr = fr.divmod(SECONDS_IN_DAY) # 4p
    h,ss = ss.divmod(3600)
    min,s  = ss.divmod(60)
    return h,fr
  end

所以我去看了documentation(1.9),并没有这种方法的痕迹.我知道这是一个愚蠢的问题,但为什么他们删除它?甚至有关于如何在/usr/lib/ruby/1.9.1/date.rb中使用该方法的示例:

def secs_to_new_year(now = DateTime::now())
     new_year = DateTime.new(now.year + 1,1,1)
     dif = new_year - now
     hours,mins,secs,ignore_fractions = Date::day_fraction_to_time(dif)
     return hours * 60 * 60 + mins * 60 + secs
 end

但我仍然得到错误

test.rb:24:in `secs_to_new_year': private method `day_fraction_to_time' called for Date:Class (NoMethodError)
    from test.rb:28:in `<main>'

解决方法

我不知道为什么它是私有的,但你仍然可以访问它:
hours,frac = Date.send(:day_fraction_to_time,stop-start)

这样你就可以覆盖OOP封装机制……这不是一件好事,但它确实有效.

原文链接:https://www.f2er.com/ruby/267956.html

猜你在找的Ruby相关文章