Tuesday, June 2, 2009

I Love Ruby on Rails! Code Snippet for Comma Separate List


I love Rails. I really do. It's by far the coolest language I've ever used. Just as an example, today I was printing out destinations that a user has visited. I created an array, looped through it, and printed each destination, followed by a comma. Now the last element would always have a comma after it, so I was thinking of a better way to implement this, instead of just removing the last comma after I had created the list. That's a lot of work to just create a damn list.

Well, of course Rails has a helper method. It's the to_sentence method that you can call on an array. I just converted my object store to a collection:
@destination.collection(&:name).to_sentence

Voila!

http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Array/Conversions.html#M001173

No comments: