DEV Community

loading...

Discussion on: Daily Challenge #296 - Years to Centuries

Collapse
developman profile image
Dmitry Mineev

The ruby example

def ordinalize(number)
  case number % 10
    when 1
      "st"
    when 2
      "nd"
    when 3
      "rd"
    else
      "th"
  end
end

def test_years(years_array)
  years_array.each do |year|
    correction = 0
    if year % 100 == 0
      correction = 1
    end
    result = (year/100.0).ceil + correction
    puts "#{year} --> #{result}#{ordinalize(result)}"
  end
end

puts "Example scope:"
test_years([1999, 2011, 2154, 2259, 1124, 2000, 20000])
puts "Test scope:"
test_years([8120, 30200, 1601, 2020, 3030, 1900, 1776])

And one-line style with activesupport gem installed

 [{name: "Example", years: [1999, 2011, 2154, 2259, 1124, 2000, 20000]},
{name: "Test", years: [8120, 30200, 1601, 2020, 3030, 1900, 1776]}].
each{ |scope| puts "#{scope[:name]} scope:"; scope[:years].
each{ |year| year % 100 == 0 ? correction = 1 : correction = 0;
result = (year/100.0).ceil + correction;
puts "#{year} --> #{result.ordinalize}" }}