Main Content

1st, 2nd, 3rd revisited in Ruby

Archive - Originally posted on "The Horse's Mouth" - 2006-12-02 17:15:03 - Graham Ellis

I've been updating some of my Ruby examples today (as one does on a Saturday!) and I thought back to the post I made yesteday concerning 1st, 2nd, 3rd, etc in Python.

Ruby has a case statement, even though Ruby is a bit of a cross between Python and Perl, neither of which supports the structure. Historically, it's been difficult for language authors to come up with a really good multiple way switch but actually the Ruby one is rather smart. Compare this Ruby to the Python code I wrote yesterday:

case value
when 1,21,31
  suffix = "st"
when 2,22
  suffix = "nd"
when 3,23
  suffix = "rd"
else
  suffix = "th"
end

puts "It is the #{value}#{suffix} of the month"


Oh - I'm revising this for the public Ruby course that's running on 14th and 15th December ... places still available at £550.00 (first delegate) and £440.00 (second and subsequent delegate on same running of the course / same order. Maximum of 7 delegates taken, and just 3 rooms available as I write, Hurry hurry hurry!!