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
@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 ','
Or use the proc short-hand:
@fruit_string = @fruit.map(&:fruit_name).join(',')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With