Rails map_with_index?
I have the following:
:participants => item.item_participations.map { |item|
{:item_ima开发者_StackOverflowge => item.user.profile_pic.url(:small)}
}
I want this to happen no more than 3 times inside. I tried map_with_index but that did not work.
Any suggestions on how I can break after a max of 3 runs in the loop?
As of Ruby 1.9, you can use map.with_index:
:participants => item.item_participations.map.with_index { |item, idx|
{:item_image => item.user.profile_pic.url(:small)}
break if i == 2
}
Although I kind of prefer the method proposed by Justice.
my_array.take(3).map { |element| calculate_something_from(element) }
You need to slice
the array, perform map
on that set, then concatenate the rest of the array to the end of the returned array from map
.
:participants => (item.item_participations[0..2].map { |item|
{:item_image => item.user.profile_pic.url(:small)}
} + item.item_participations[3..-1])
Here's an example:
精彩评论