When learning Ruby on Rails, sometimes you just need to get the current year as a number. I posted one example on why this is a useful way on a real-life website in the 2011 post on how to automatically update copyright notices.
In this article, I will show you some methods for getting the current year, such as the number
2015. I will then show you how to benchmark the methods to determine which is the fastest method for you, given your machine and Ruby version.
Okay, just how do I get the Current Year in Ruby?
It’s easy. Just use any of the Date/Time objects and call the
year method, like this:
1 2 3 4 5 6 7 8
If you want to just throw this information in a view, then something like this in your ERB should be good.
1 2 3
And, if you want the numerical month of the year
Benchmarking the performance of the options
If you are into profiling code, check out Joshua McGees’ 2013 post on the same topic, Getting the current year in Ruby on Rails (eclecticquill.com). According to his findings with Ruby at the time,
Time.new.year was significantly faster than
Date.current.year (which is available in Ruby on Rails, but is not in the standard Ruby library).
I have decided to try out the same benchmark test on my 2014 MacBook Pro, a 2.8 GHz Intel Core i7.
The benchmark code that I ran in IRB
1 2 3 4 5 6 7 8 9
|Method||Ruby 2.2||JRuby 1.7.19|
The fastest methods are bolded.
Time.new.year seems to be a good balance on performance if you are using either the latest MRI, Ruby 2.2 or JRuby at the time of this writing.
I hope this helps you learn a little bit more about Ruby. It really is one of the best, most fun programming languages to work in. A good next step is to checkout the relevant Ruby standard library documentation on Date/Time classes at: