CommonThread

Tip: Ruby on Rails Array to_sentence

Posted by anthony crumley, Tue Nov 27 07:36:00 UTC 2007

Ruby on Rails extends many of the Ruby types with interesting and often useful methods. The to_sentence method on arrays returns the values in an array separated by commas with a conjunction between the last two. There are two options. :connector provides the conjunction with ‘and’ being the default. :skip_last_comma is a boolean that determines whether or not the last comma is displayed and the default is false.

favorite_fruit = ['apples', 'oranges', 'grapes']
puts "My favorite fruits are #{favorite_fruit.to_sentence}." 

Result:

My Favorite fruits are apples, oranges, and grapes.

Filed Under: Ruby on Rails | Tags:

Comments

  1. Ben 11.27.07 / 15PM
    if the default value for :skip_last_comma is true and you didn't override it in your call to to_sentence ... why is there a comma before the and?
  2. Anthony 11.27.07 / 17PM
    I was just seeing if anyone was paying attention. :)

Have your say

A name is required. You may use HTML in your comments.




Categories