Search code examples
ruby-on-railsrubyruby-on-rails-3rubygems

Ruby method to get the months of quarters a given date belongs to


I have a date and i want to find out the months of that particular quarter.How can i have this done in ruby in the easiest possible way? I mean if the date i give is 27-04-2011, then the result i must get is April, May,June as string or int like 4,5,6 for April to June.


Solution

  • You can define a function for that to accept the date as argument and return the quarter

    def current_quarter_months(date)
      quarters = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
      quarters[(date.month - 1) / 3]
    end
    

    The function will return array based on the the value of the quarter the date belongs to.