Ruby, get hours, seconds and time from Date.day_fraction_to_time
Asked Answered
D

2

7

I've found this method 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)

I have the following error:

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

I've checked /usr/lib/ruby/1.9.1/date.rb and I've found it:

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

But I have no problem if I run it with ruby1.8. /usr/lib/ruby/1.8/date.rb gives me:

  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, min, s, fr
  end

So i went to see the documentation(1.9) and there's no trace of this method. I know it's a dumb question, but why did they remove it? There is even this example on how to use the method in /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

but I'm still getting the error:

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>'
Darnel answered 16/9, 2010 at 22:54 Comment(0)
A
3

I don't know why it was made private, but you can still access it:

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

This way you override the OOP encapsulation mechanizm... This is not a very nice thing to do, but it works.

Anthropometry answered 18/9, 2010 at 9:51 Comment(1)
Exactly. I'm breaking the OOP structure, so annoying. Isn't it __send__ ?Darnel
D
0

I've found another method which seems more elegant to me:

start = DateTime.now
sleep 3
stop = DateTime.now

puts "Date.day_fraction_to_time using wrapper"
class Date
    class << self
      def wrap_day_fraction_to_time( day_frac )
        day_fraction_to_time( day_frac )
      end
   end
end
hours, minutes, seconds, frac =
    Date.wrap_day_fraction_to_time( stop - start )
p hours, minutes, seconds, frac

Thanks to Colin Bartlett from ruby-forum.com

To understand how it works I suggest to read David Seiler's answer

Darnel answered 18/9, 2010 at 11:34 Comment(2)
This is more elegant in fact, in some way, but on the other hand - monkey patching builtin classes is also a thing which is seen as "bad practise"...Anthropometry
yep, but right now I'm out of ideas. I mean I can of course write a function ex novo but it annoys me that a method is available and I can't use it.Darnel

© 2022 - 2024 — McMap. All rights reserved.