Thursday, November 01, 2007
Rails: Array#to_sentence
Documentation
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
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
endLabels: activesupport, rails
Comments:
<< Home
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.
User: Jared. Roles: admin, editor and contributor.
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
Post a Comment
array.select { |element| not element.blank? }
Cheers, Jay
<< Home



