0

I feel like this is such an easy question

<% @state.cities.each do |city| %>
   <%= city.id %>
<% end %>

puts the ids as follows:

1
2
3 etc...

How do I turn the iteration into an array?

so it outputs as follows:

[1,2,3,4,etc...] 
1
  • Why downvoting without explaining why ? Completely useless. If you think the question needs improvement or shouldn't be here, explain it to the OP so he/she learns. Commented Dec 13, 2016 at 22:09

3 Answers 3

3

There is a method that does just that!

What you are looking for is the map method.

Creates a new array containing the values returned by the block.

http://apidock.com/ruby/Array/map

The documentation states, creates an array containing the values returned by a block.

@state.map do |state|
  state.id
end
=> [1,2,3,...]

Which is the same as:

@state.map(&:id)
=> [1,2,3,...]

But uses the Ruby Enumerable shorthand.

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

Comments

2

@state.map(&:id) would give you the same result!

Comments

2

You can use map:

<%= @state.map(&:id) %>

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.