How to convert an array to comma delimited string using ruby

This is one example.

(Category.find(:all,:select => "name").collect {|c| c.name}).join(', ') 

It generates:

 "Category1, Category2" 

Is there any other, more efficient + cleaner way to do this?

+4
source share
3 answers

The problem is that you are trying to join the attribute of the objects, not the objects themselves. Gathering is the best way I know this. But I would use the to_sentence method to_sentence Rails provides the conversion of arrays exactly like this:

 Category.find(:all,:select => "name").collect { |c| c.name }.to_sentence 
+10
source

No, your decision looks quite normal.

You can only drop parentheses to join .

+3
source

Array.pluck will put it in an array of strings for you. Big savings will not lead to the creation of Ruby ActiveRecord objects when you do not need them.

 Category.pluck(:name).join(", ") Category.pluck(:name).to_sentence 
0
source

All Articles