class Numeric
  def to_ordinal
    to_i.to_s + ((11..13) === (n = to_i.abs % 100) ? 'th' :
      { 1 => 'st', 2 => 'nd', 3 => 'rd' }.fetch(n % 10, 'th'))

This code is based on a snippet for generating ordinals. The other examples used a fixed-size array for pulling suffixes. Instead, I use the 2-parameter version of Hash#fetch to supply a default for most numbers.

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.