Skip to content

Commit 5cb7d74

Browse files
committed
Add Shift The Month On A Date Object as a Ruby TIL
1 parent 127329e commit 5cb7d74

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1324 TILs and counting..._
13+
_1325 TILs and counting..._
1414

1515
---
1616

@@ -1116,6 +1116,7 @@ _1324 TILs and counting..._
11161116
- [Scripting With RVM](ruby/scripting-with-rvm.md)
11171117
- [Scroll To Top Of Page With Capybara](ruby/scroll-to-top-of-page-with-capybara.md)
11181118
- [Set RVM Default Ruby](ruby/set-rvm-default-ruby.md)
1119+
- [Shift The Month On A Date Object](ruby/shift-the-month-on-a-date-object.md)
11191120
- [Show Public Methods With Pry](ruby/show-public-methods-with-pry.md)
11201121
- [Silence The Output Of A Ruby Statement In Pry](ruby/silence-the-output-of-a-ruby-statement-in-pry.md)
11211122
- [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)