htatche
htatche

Reputation: 693

Shortest way to obtain last day of previous month with Ruby

Is there a shorter/more elegant way to reformulate this expression whilst achieving the same result ?

Date.today.last_month.end_of_month

Upvotes: 3

Views: 2069

Answers (2)

Mayank
Mayank

Reputation: 727

The one you've already written is short and elegant enough still you can try these

Date.today - Date.today.day

or even shorter version will be to use a variable to limit the words you can try:

(a=Date.today) - a.day

Hope this helps

Upvotes: 6

Mark Bolusmjak
Mark Bolusmjak

Reputation: 24399

You want the end of the month. For which month? The last one. Last with respect to what? Today.

So you have said exactly what you are looking for and got it. What is inelegant about that?

If you want shorter:

def end_of_last_month
  Date.today.last_month.end_of_month
end

Upvotes: 4

Related Questions