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

About this user

Kevin

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

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

   1  
   2  def number_to_ordinal(num)
   3    num = num.to_i
   4    if (10...20)===num
   5      "#{num}th"
   6    else
   7      g = %w{ th st nd rd th th th th th th }
   8      a = num.to_s
   9      c=a[-1..-1].to_i
  10      a + g[c]
  11    end
  12  end
  13  
  14  number_to_ordinal(12) => "12th"
  15  number_to_ordinal(7) => "7th"


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

Write out an array as a list with commas and an 'and'

Actually, you can customize the separators to your needs.

   1  
   2  def text_list(listtext,sep1=", ", sep2=", and ")
   3    n=listtext.size
   4    if n>1 : (listtext.first(n-1)).join(sep1) + sep2 +listtext.last 
   5    else listtext.first end
   6  end
   7  
   8  text_list(["cat", "dog", "bird"]) => "cat, dog, and bird"
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS