|
| 1 | +# Shift The Month On A Date Object |
| 2 | + |
| 3 | +One of things that Ruby loves to do is overload operators to support |
| 4 | +specialized class-specific functionality. For instance, with the `Date` class, |
| 5 | +you can use the `+` and `-` operators to add or remove days from a given |
| 6 | +`Date`. |
| 7 | + |
| 8 | +```ruby |
| 9 | +> Date.today |
| 10 | +=> #<Date: 2023-07-13 ((2460139j,0s,0n),+0s,2299161j)> |
| 11 | +> Date.today + 1 |
| 12 | +=> #<Date: 2023-07-14 ((2460140j,0s,0n),+0s,2299161j)> |
| 13 | +> Date.today - 3 |
| 14 | +=> #<Date: 2023-07-10 ((2460136j,0s,0n),+0s,2299161j)> |
| 15 | +``` |
| 16 | + |
| 17 | +That one feels pretty natural to me. |
| 18 | + |
| 19 | +The `Date` class overloads another operator to do something that doesn't feel |
| 20 | +quite as natural. |
| 21 | + |
| 22 | +The `<<` operator will shift (increment or decrement) the month of the given |
| 23 | +`Date` object. Given a positive number, it will shift the date that many months |
| 24 | +in the future (even wrapping to a new year as necessary). Given a negative |
| 25 | +number, it will shift the date back in time that many months. |
| 26 | + |
| 27 | +```ruby |
| 28 | +> Date.today |
| 29 | +=> #<Date: 2023-07-13 ((2460139j,0s,0n),+0s,2299161j)> |
| 30 | +> Date.today << 1 |
| 31 | +=> #<Date: 2023-06-13 ((2460109j,0s,0n),+0s,2299161j)> |
| 32 | +> Date.today << -2 |
| 33 | +=> #<Date: 2023-09-13 ((2460201j,0s,0n),+0s,2299161j)> |
| 34 | +> Date.today << 6 |
| 35 | +=> #<Date: 2023-01-13 ((2459958j,0s,0n),+0s,2299161j)> |
| 36 | +``` |
| 37 | + |
| 38 | +This is a bit clever for my liking, but fun to know about. |
| 39 | + |
| 40 | +[source](https://ruby-doc.org/stdlib-3.0.0/libdoc/date/rdoc/Date.html#method-i-3C-3C) |
0 commit comments