Rails map_with_index?

I have the following:

:participants => item.item_participations.map { |item| {:item_image => item.user.profile_pic.url(:small)} } 

I want this to happen no more than three times inside. I tried map_with_index but that did not work.

Any suggestions on how I can break down after no more than 3 cycles are executed in a loop?

+6
ruby
source share
3 answers
 my_array.take(3).map { |element| calculate_something_from(element) } 
+9
source share

Starting with 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 prefer the method proposed by justice.

+21
source share

You need a slice array, execute map in this set, and then merge the rest of the array at the end of the returned array with map .

 :participants => (item.item_participations[0..2].map { |item| {:item_image => item.user.profile_pic.url(:small)} } + item.item_participations[3..-1]) 

Here is an example:

alt text

+1
source share

All Articles