Here’s a quick and simple Ruby method I wrote that turns an array into a nice, formatted list.

def list(array, options={})
  options[:conjunction] ||= "and"

  list = ""
  array.each_with_index do |string, index|
    list += " " if array.size == 2
    list += options[:conjunction] += " " if array.size == (index + 1)
    list += string.to_s
    list += ", " unless array.size == (index + 1) or array.size == 2
  end

  list = "nothing" if list.empty?
  return list
end

Using it should be fairly obvious if you’re familiar with Ruby.

fruits = ["apple", "banana", "peach", "mango"]
list fruits #=> "apple, banana, peach and mango"

numbers = [1, 2]
list fruits, :conjunction => "or" #=> "1 or 2"

empty = []
list empty #=> "nothing"

Since I’m fairly new to Ruby, the way that I’m doing this probably isn’t the most efficient ever, so feel free to sound off in the comments with any improvements.

Update: list() now returns “nothing” instead of (literally) nothing if the array is empty.

Update 2: Apparently, Rails already had a (much better) alternative—Array.to_sentence. Whoops. (Thanks, Noah)

145 words 2 comments

Hello! We all look forward to hearing from you!

required, but never displayed or shared! (optional, of course) http://
  • You know there is a function to do that built into Rails, right? (God, I feel like I say that a lot :P )

    You can use the to_sentence method, does pretty much the exact same thing :P

    http://api.rubyonrails.org/.../Conversions.html

    Noah 2008.04.14

  • Noah: Wow, I can't believe I didn't find that!

    River 2008.04.14