Thursday, November 01, 2007

Rails: Array#to_sentence

Documentation
Converts the array to comma-seperated sentence where the last element is joined by the connector word. Options:
  • :connector: The word used to join the last element in arrays with two or more elements (default: "and")
  • :skip_last_comma: Set to true to return "a, b and c" instead of "a, b, and c".
Usage
Array#to_sentence is perfect for joining information stored in an array that needs to be presented in a human readable format (e.g. an array of errors).

Test

require 'rubygems'
require 'active_support'
require 'test/unit'
require 'dust'

unit_tests do
test "words are joined nicely" do
expected = "one, two, and three"
assert_equal expected, ['one', 'two', 'three'].to_sentence
end
end

3 comments:

  1. Anonymous11:31 AM

    I use this all the time, particularly for things like user roles, it gives me a nice clean list like:
    User: Jared. Roles: admin, editor and contributor.

    ReplyDelete
  2. How do you test if the elements in the array you want to use .to_sentence on are not nil or empty?

    ReplyDelete
  3. Anonymous7:28 AM

    Instead of testing, just use compact to remove nils, or use select if you want greater control.

    array.select { |element| not element.blank? }

    Cheers, Jay

    ReplyDelete

Note: Only a member of this blog may post a comment.