firstruby

Master ruby with us

Archive for July, 2009

‘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"

Posted in firstruby, Useful Links | Leave a Comment »