Ordinal Numbers Done Right
irb(main):011:0> 112.ordinal
=> "112nd"
Wow thats WRONG. So, I fixed it:
class Numeric
def ordinal
cardinal = self.to_i.abs
if (10...20).include?(cardinal%100) then
cardinal.to_s << 'th'
else
cardinal.to_s << %w{th st nd rd th th th th th th}[cardinal % 10]
end
end
end
irb(main):011:0> 112.ordinal
=> "112th"
irb(main):012:0> 1234.ordinal
=> "1234th"
irb(main):013:0> 1211.ordinal
=> "1211th"
Yes, I know, I saved the day. Again.


Benjamin
August 15, 2006 at 5:41 PM
I love ordinals. Nicely done there, way to save the day as you said! hee – ben @ http://rubyonrailsblog.com/