firstruby

Master ruby with us

‘ordinalize’ in Ruby On Rails

Posted by firstruby on July 21, 2009

Print numbers as Cardinals in Ruby On Rails (like 1st, 2nd, 3rd, 4th and so on….)

Rails has inbuilt function – ordinalize

(1).ordinalize => "1st"
(13).ordinalize => "13th"
(22).ordinalize => "22nd"
(100).ordinalize => "100th"

Also we can write the helper as following,

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(23) => "23rd"
number_to_ordinal(1) => "1st"

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: