## DEV Community is a community of 621,723 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: Daily Challenge #296 - Years to Centuries

3limin4t0r • Edited

This might be a bit over-engineered, but here is another Ruby solution:

``````def to_century(year)
(year.to_i / 100 + 1).english.ordinal
end

class Integer
def english
English::Integer.new(self)
end
end

module English
class Integer
def initialize(integer)
@value = integer
end

##
# Returns ordinal notation of the current integer ("-2nd", "1st", "312th").
def ordinal
"#{@value}#{ordinal_suffix}"
end

##
# Returns the ordinal suffix of the current integer ("st", "nd", "rd", "th").
def ordinal_suffix
case @value.abs % 100
when 1, 21, 31, 41, 51, 61, 71, 81, 91 then 'st'
when 2, 22, 32, 42, 52, 62, 72, 82, 92 then 'nd'
when 3, 23, 33, 43, 53, 63, 73, 83, 93 then 'rd'
else 'th'
end
end
end
end
``````

Which produces the following output:

``````years = %w[8120 30200 1601 2020 3030 1900 1776]
years.to_h { |year| [year, to_century(year)] }
#=> {"8120"=>"82nd", "30200"=>"303rd", "1601"=>"17th", "2020"=>"21st", "3030"=>"31st", "1900"=>"20th", "1776"=>"18th"}
``````