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
unit_tests do
test "words are joined nicely" do
expected = "one, two, and three"
assert_equal expected, ['one', 'two', 'three'].to_sentence
end
end
I use this all the time, particularly for things like user roles, it gives me a nice clean list like:
ReplyDeleteUser: 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?
ReplyDeleteInstead of testing, just use compact to remove nils, or use select if you want greater control.
ReplyDeletearray.select { |element| not element.blank? }
Cheers, Jay