我有以下内容:
: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提出的方法.
my_array.take(3).map { |element| calculate_something_from(element) }
Run Code Online (Sandbox Code Playgroud)