"Which Century" programming exercise I recently wrote this up and am wondering if there is a better way to achieve the results I want.

Essentially, we're taking a given year and adding 'th, nd, rd, st' depending on the digit.

Any suggestions on how to shorten this code and make it better?

Keep in mind that this is taking centuries that change every 01st year. For example, year 2000 is the 20th century, but 2001 is the 21st century.

def which_century(string)
  year = string.to_i
  modifier = 1

  return "1st century" if year &lt; 101

  if year &gt; 100 &amp;&amp; string.end_with?("00")
    modifier -= 1
  end

  century = year / 100 + modifier
  p century
  if century &gt; 10 &amp;&amp; century &lt; 20 
    return century.to_s &lt;&lt; "th century."
  end

  second_digit = century % 10

  case second_digit
  when 1 then century.to_s &lt;&lt; "st century"
  when 2 then century.to_s &lt;&lt; "nd century"
  when 3 then century.to_s &lt;&lt; "rd century"
  else
    century.to_s &lt;&lt; "th century"
  end
end

puts "Type in a year:"
answer = gets.chomp
p which_century(answer)
Let's clarify the logic.  The code simplification will follow.  The rules are:


"th" years are those ending in 4, 5, 6, 7, 8, 9, or 0.  Additionally, the 11th, 12th, and 13th centuries are exceptions also ending in "th".
Years ending in 1 are "st" years.
Years ending in 2 are "nd" years.
Years ending in 3 are "rd" years.


Now just translate the above into code:

def which_century(string)
  century  = (string.to_f / 100).ceil
  year     = century % 10
  nth_year = (11..13).include?(century) || !(1..3).include?(year)
  return "#{century}th century" if nth_year
  return "#{century}st century" if year == 1
  return "#{century}nd century" if year == 2
  return "#{century}rd century" if year == 3
end