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...]
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.
您可以使用map
:
<%= @state.map(&:id) %>
@state.map(&:id)
会给您相同的结果!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.