Adt
Adt

Reputation: 495

How to find array of months from current month with a step of x months

I want to generate an array of months such that it contains the current month and all months after a particular gap.

For example, Find 3 months steps from the current month in a year.

Something like:

def months_from(offset:, current_month)
...
end

So, for months_from(offset: 3.months, current_month: 8) it gives [8, 11, 2, 5]

and for months_from(offset: 6.months, current_month: 8) it gives [8, 2] and soo on.

How can I write months_from method? Is there something in ruby/rails to achieve this?

Upvotes: 0

Views: 141

Answers (1)

Lutfi Fitroh Hadi
Lutfi Fitroh Hadi

Reputation: 169

ruby Date class has the .next_month(integer) method that will automatically add several months from your provided date. So for your question, it can be done like this:

def months_from(offset, current_month)
    result = [current_month]
    loop = 12/offset # we need to find how many times is the steps in a year

    (1...loop).each do |index|
        result << Date.strptime(current_month.to_s, '%m').next_month(offset*index).strftime('%m').to_i
        
    end

    result
end

Upvotes: 1

Related Questions