开发者

Activerecord Array of Objects to comma separated string

开发者 https://www.devze.com 2023-02-07 23:58 出处:网络
Say I have a model called \"Fruit\" and a query is returning all the distinct fruit names to @fruit:

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 (acti开发者_如何学编程verecord 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 ','


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.


Or use the proc short-hand:

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

精彩评论

暂无评论...
验证码 换一张
取 消