Ruby ، ​​احصل على ساعات ، ثواني ووقت من Date.day_fraction_to_time

StackOverflow https://stackoverflow.com/questions/3731468

سؤال

لقد وجدت هذه الطريقة هنا.

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

لذلك ذهبت لرؤية الوثائق (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,minutes,seconds,frac = Date.send(:day_fraction_to_time, stop-start)

وبهذه الطريقة ، تقوم بتجاوز ميكانيكية تغليف OOP ... هذا ليس شيئًا لطيفًا جدًا ، لكنه يعمل.

نصائح أخرى

لقد وجدت طريقة أخرى تبدو أكثر أناقة بالنسبة لي:

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

بفضل كولين بارتليت ruby-forum.com

لفهم كيف تعمل إجابه

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top