Mike Mike - 1 month ago 6
Ruby Question

How do I compare month-year combinations in Ruby?

I’m using Rails 4.2.7. I have two pairs of numbers …

month1 # A number between 1 and 12
year1 # a four digit year
month2 # A number between 1 and 12
year2 # A four digit year


How do I write a comparison expression to determine if the “month2-year2” combination is greater than or equal to the “month1-year1” combination? For instance if month2 = 1 and year2 = 2017 and month1 = 12 and year1 = 2016, the month2-year2 combination is greater than the month1-year1 combination.

Answer
month1, month2, year1, year2 = 12, 1, 2016, 2017
=> [12, 1, 2016, 2017]
Time.new(year1, month1) >= Time.new(year2, month2)
=> false
Time.new(year2, month2) >= Time.new(year1, month1)
=> true

reference: https://ruby-doc.org/core-2.2.0/Time.html#class-Time-label-Creating+a+new+Time+instance