10

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

2 Answers 2

34
@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.

Sign up to request clarification or add additional context in comments.

1 Comment

I would use the shorthand version below
17

Or use the proc short-hand:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.