Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activerecord Array of Objects to comma separated string

Say I have a model called "Fruit" and a query is returning all the distinct fruit names to @fruit:

  • !ruby/object:Fruit attributes: fruit_name: orange attributes_cache: {}

  • !ruby/object:Fruit attributes: fruit_name: apple attributes_cache: {}

  • !ruby/object:Fruit attributes: fruit_name: peach attributes_cache: {}

I understand (somewhat) @fruit is an Array made up of Arrays (activerecord objects). I'm trying to get the returned fruit names into a comma separated string, like: "orange,apple,peach".

If the array was made up of strings or numbers (instead of arrays), I know I could use map w/ .join(',') to do this. I'm having trouble with the extra syntax needed to refer to the arrays in the array (the 'fruit_name' fields of the arrays at each array index).

I know this would work, just not sure how to do this as a dynamic iteration:

@fruit_string = @fruit[0].fruit_name + ',' + @fruit[1].fruit_name + ',' + @fruit[2].fruit_name

like image 597
Reno Avatar asked Jan 30 '11 00:01

Reno


2 Answers

@fruit_string = @fruit.map { |f| f.fruit_name }.join ','

Now, when a block consists of a method call with no parameters, and for somewhat complicated1 reasons, you can write it like

@fruit_string = @fruit.map(&:fruit_name).join ','


1. The unary & operator turns procs into blocks and blocks into procs. If the operand is neither, then it first calls to_proc, if it can. (And yes, Symbol has a to_proc.) It's even more complicated than that, but that's the reason why it's a nice pithy complement to map.
like image 105
DigitalRoss Avatar answered Dec 01 '22 20:12

DigitalRoss


Or use the proc short-hand:

@fruit_string = @fruit.map(&:fruit_name).join(',')
like image 34
Toby Hede Avatar answered Dec 01 '22 22:12

Toby Hede