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 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?
You use map to collect the result of running the block over the elements of the array. And you use each to run the block over the elements without collecting the values. You can read more about using the each method here.
So each is used for processing an array and map is used to do something with a processed array.
In a method argument list, the & operator takes its operand, converts it to a Proc object if it isn't already (by calling to_proc on it) and passes it to the method as if a block had been used.
Ruby Map SyntaxFirst, you have an array, but it could also be a hash, or a range. Then you call map with a block. The block is this thing between brackets { ... } . Inside the block you say HOW you want to transform every element in the array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With