Converts the array to comma-seperated sentence where the last element is joined by the connector word. Options:Usage
- :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".
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:
I use this all the time, particularly for things like user roles, it gives me a nice clean list like:
Reply DeleteUser: Jared. Roles: admin, editor and contributor.
How do you test if the elements in the array you want to use .to_sentence on are not nil or empty?
Reply DeleteInstead of testing, just use compact to remove nils, or use select if you want greater control.
Reply Deletearray.select { |element| not element.blank? }
Cheers, Jay
Note: Only a member of this blog may post a comment.
[フレーム]