Suppose I have a some kind of object that represents a person, and they have a date of birth:

@user = User.create(
:birthday => Date.parse('01-01-1901')
)

How do you find out of today is their birthday?

You could compare :birthday with Date.today, but that would fail since the years will be different.

You could use the Date Class method ‘yday’, which returns the day of the year, and compare them but that will fail after any leap year has passed.

You could get :birthday’s year (@user.birthday.year), then convert :birthday to a string and replace ’1901′ with the current year, run that back through Date.parse and then compare it with Date.today… but that seems like a lot of slow steps.

There’s an easier way though, since we don’t actually care about the year at all.

Instead, compare just the month and the day:

@user.birthday.day == Date.today.day && @user.birthday.month == Date.today.month

That will compare just on the month and day and ignore the year. But that’s two comparison and two instantiations of the Date class, and we can do better:


def same_day?(date)
today = Date.today
"#{date.mday} #{date.mon}" == "#{today.mday} #{today.mon}"
end

same_day?(@user.birthday)

There you go. You may ask why not use “strftime” to format the string and compare that? Because that can be really slow on some systems.