开发者

Rails map_with_index?

开发者 https://www.devze.com 2023-02-01 05:03 出处:网络
I have the following: :participants => item.item_participations.map { |item| {:item_ima开发者_StackOverflowge => item.user.profile_pic.url(:small)}

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:

Rails map_with_index?

0

精彩评论

暂无评论...
验证码 换一张
取 消