Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Helper to print numbers as ordinals (1st, 2nd, 3rd...) (See related posts)

def number_to_ordinal(num)
  num = num.to_i
  if (10...20)===num
    "#{num}th"
  else
    g = %w{ th st nd rd th th th th th th }
    a = num.to_s
    c=a[-1..-1].to_i
    a + g[c]
  end
end

number_to_ordinal(12) => "12th"
number_to_ordinal(7) => "7th"


Note that floats will be converted to ints (without rounding) before processing.

Comments on this post

robertbrook posts on Sep 14, 2005 at 12:47
How about

class Numeric
	def ordinal
		(10...20) === self ? "#{self}th" : self.to_s + %w{ th st nd rd th th th th th th }[self.to_s[-1..-1].to_i]
	end
end

p 2.ordinal
p 20.ordinal
p 23.ordinal
p (0xA8).ordinal
robertbrook posts on Sep 14, 2005 at 13:01
Or even:

class Numeric
	def ordinal
		self.to_s + ( 10...20 === self ? 'th' : %w{ th st nd rd th th th th th th }[self[-1]] )
	end
end
canadaduane posts on Sep 23, 2005 at 02:01
In case that didn't work for you, here's my version:
class Numeric
	def ordinal
		self.to_s + ( (10...20).include?(self) ? 'th' : %w{ th st nd rd th th th th th th }[self % 10] )
	end
end

You need to create an account or log in to post comments to this site.


Click here to browse all 5143 code snippets

Related Posts