How to convert 1 to "first", 2 to "second", and so on, in Ruby?

Viewed 8653

Is there a built-in method in Ruby to support this?

5 Answers

if you are not in Rails you could do

def ordinalize(n)
  return "#{n}th" if (11..13).include?(n % 100)

  case n%10
  when 1; "#{n}st"
  when 2; "#{n}nd"
  when 3; "#{n}rd"
  else    "#{n}th"
  end
end

ordinalize 1
=> "1st"
ordinalize 2
=> "2nd"
ordinalize 11
=> "11th"
Related