| Written by


Working on our latest Sinatra project, I came across the need to turn an array of words into a list to plug into a sentence. I like to crib Rails code whenever possible, because the project has a ton of useful extensions for this type of task, however I couldn’t find anything that exists for turning arrays into an English style list. So for that I came up with listify!
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!

  • RC

    Cool.

  • http://www.facebook.com/profile.php?id=643621205 Bradley Priest

    Couldn’t you just use ActiveSupport’s to_sentence?

    • Gavin Miller

      Didn’t know that to_sentence existed in ActiveSupport. Went looking, but clearly not the right place. Thanks for the info.

  • Robert Head

    [["dave"], ["dave", "bill"], ["dave", "bill", "murry"]].each do |list|
      list.listify.should == list.to_sentance
    end

    • Robert Head

      to_sentence

  • Anonymous

    to_sentence exists and it’s i18n-ready

  • http://twitter.com/peterc Peter Çoopèr

    A list of two items wouldn’t have a comma after the first item, by the way. Strunk specifically refers to three or more :-)

    • Gavin Miller

      Thanks for the feedback peter. Also, really like your golfing. Had to try it in irb to see what would happen on the [] case. Elegant solution.