Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>EDIT</strong>: Take a look at <a href="https://stackoverflow.com/questions/238878/is-it-acceptable-practice-to-patch-rubys-base-classes-such-as-fixnum">this question</a> before you decide to use the approach I've outlined here. It seems it may not be best practice to modify the behavior of a base class in Ruby (which I can understand). So, take this answer with a grain of salt...</p> <hr> <p><a href="https://stackoverflow.com/questions/238684/subtract-n-hours-from-a-datetime-in-ruby#238690">MattW's answer</a> was the first thing I thought of, but I also didn't like it very much.</p> <p>I suppose you could make it less ugly by patching <code>DateTime</code> and <code>Fixnum</code> to do what you want:</p> <pre><code>require 'date' # A placeholder class for holding a set number of hours. # Used so we can know when to change the behavior # of DateTime#-() by recognizing when hours are explicitly passed in. class Hours attr_reader :value def initialize(value) @value = value end end # Patch the #-() method to handle subtracting hours # in addition to what it normally does class DateTime alias old_subtract - def -(x) case x when Hours; return DateTime.new(year, month, day, hour-x.value, min, sec) else; return self.old_subtract(x) end end end # Add an #hours attribute to Fixnum that returns an Hours object. # This is for syntactic sugar, allowing you to write "someDate - 4.hours" for example class Fixnum def hours Hours.new(self) end end </code></pre> <p>Then you can write your code like this:</p> <pre><code>some_date = some_date - n.hours </code></pre> <p>where <code>n</code> is the number of hours you want to substract from <code>some_date</code></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload