class Array
def listify
length < 2 ? first.to_s : "#{self[0..-2] * ', '} and #{last}"
end
end
Listify is an extension to Ruby’s Array class, and it will take an array of words, and turn them into a human readable list, along with the proper grammatical conventions as put forth by William Strunk. Usage is thusly:
["dave"].listify #=> "dave" ["dave", "bill"].listify #=> "dave and bill" ["dave", "bill", "murray"].listify #=> "dave, bill, and murray"
Update – Turns out that I didn’t look hard enough in Rails. Rails has a method called to_sentence which accomplishes the same end as noted above. The Rails version is great if you’re working in a Rails environment, or if you want to bring ActiveSupport into your project as a dependency.
Update 2 – Peter Cooper pointed out that my Stunk usage was incorrect for two commas, and added a nice little golf solution. I’ve updated the post to reflect this feedback. Thanks everyone for the constructive criticism!