I'm switching to Ruby from Java and so, for exercise purposes, I wrote this verbose leap year Ruby program. The comments express my concerns about Ruby best practices. I'd be glad if some Ruby experienced programmer could dispel my doubts. Every hint such as "in Ruby you can achieve this thing better this way" is truly welcomed.
First of all, this is a possible execution:
Pick a starting year: 2000 Now pick an ending year: 2024 From year 2000 to year 2024 there are 7 leap years. Specifically: The year 2000 was a leap year, The year 2004 was a leap year, The year 2008 was a leap year, The year 2012 is a leap year, The year 2016 will be a leap year, The year 2020 will be a leap year, The year 2024 will be a leap year.
Please note the verb conjugation and that every line has a comma at the end, except the last one that has a period.
# I just felt bad about calling Time.now.year every time just to know the present year,
# is this simple memoization a good solution?
def was_is_or_will_be(year)
@present ||= Time.now.year
return 'is' if year == @present
return 'was' if year < @present
return 'will be' if year > @present
end
# first of all, let's ask for the years interval
puts 'Pick a starting year:'
starting = gets.chomp.to_i
puts 'Now pick an ending year:'
# Is this the best "repeat..until" pattern for ruby?
# Because it doesn't seems very clear to me.
# There is no way to write somethin more explicit like a "do..while"?
while true
ending = gets.chomp.to_i
if ending > starting
break
end
puts "The ending year must be greater than the starting year,\n please pick a valid ending year:"
end
# This piece of code seems 'ruby-way' to me... isn't it?
leap_years = []
(starting..ending).each do |year|
if year%4 == 0 && (year%100 != 0 || year%400 == 0)
leap_years << year
end
end
# This is the best way I found to handle this simple pluralization
puts "From year #{starting} to year #{ending} there #{leap_years.count == 1 ? 'is' : 'are'} " +
"#{leap_years.count} leap #{leap_years.count == 1 ? 'year' : 'years'}."
# If there are some leap_years in the interval I want a verbose list of them
if leap_years.count > 0
puts "Specifically:"
# Is there a way to achieve the same function (a comma at the end of every line but a period at the end of the last one)
# Without an 'i' counter? With such as a Java 'hasNext()' equivalent?
i = 1;
leap_years.each do |leap_year|
puts "The year #{leap_year} #{was_is_or_will_be(leap_year)} a leap year#{ i < leap_years.count ? ',' : '.'}"
i += 1
end
end