Converting arrays to sentences in Ruby
I often find myself needing to convert an array of elements into a sentence in the view in my Ruby on Rails applications. For example, turning the array ['dog', 'cat', 'mouse'] into the text "dog, cat, and mouse".
Turns out, there is an array method called to_sentence that will perform this conversion automatically: arrayName.to_sentence. The to_sentence method allows you to control the connecting word ("and" in this case), and if there should be a comma placed before the connecting word. If your writing applications in Ruby on Rails, this method is a nice trick to know.
Turns out, there is an array method called to_sentence that will perform this conversion automatically: arrayName.to_sentence. The to_sentence method allows you to control the connecting word ("and" in this case), and if there should be a comma placed before the connecting word. If your writing applications in Ruby on Rails, this method is a nice trick to know.
| Link: | api.rubyonrails.org...Search for more tips related to this link |
| Rating: | no ratings, 0 total Votes |
| Categories: | Ruby on Rails |
| Added: | on Jun 28, 2007 at 6:08 am |
| Added By: | an anonymous user |

