Rails map_with_index?

AnA*_*ice 6 ruby

我有以下内容:

    :participants => item.item_participations.map { |item|
      {:item_image => item.user.profile_pic.url(:small)}
    }
Run Code Online (Sandbox Code Playgroud)

我希望这种情况不会超过3次.我尝试了map_with_index但是没有用.

关于如何在循环中最多运行3次后如何破坏的任何建议?

Bri*_*ing 21

从Ruby 1.9开始,您可以使用map.with_index:

:participants => item.item_participations.map.with_index { |item, idx|
  {:item_image => item.user.profile_pic.url(:small)}
  break if i == 2  
}
Run Code Online (Sandbox Code Playgroud)

虽然我更喜欢Justice提出的方法.

  • 为我的问题找到了解决方案:`t('date.day_names').each_with_index.map {| day,idx | [day,idx]}` (3认同)

yfe*_*lum 9

my_array.take(3).map { |element| calculate_something_from(element) }
Run Code Online (Sandbox Code Playgroud)