Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, get hours, seconds and time from Date.day_fraction_to_time

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>'
like image 745
dierre Avatar asked Sep 16 '10 22:09

dierre


1 Answers

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.

like image 76
apirogov Avatar answered Oct 20 '22 00:10

apirogov