Ruby Rails映射有索引吗?
我有以下资料:Ruby Rails映射有索引吗?,ruby,Ruby,我有以下资料: :participants => item.item_participations.map { |item| {:item_image => item.user.profile_pic.url(:small)} } 我希望这种情况在室内发生不超过3次。我试着用索引映射,但没用 在循环中最多运行3次后,有没有关于如何中断的建议?您需要对数组进行切片,在该集合上执行映射,然后将数组的其余部分连接到映射返回的数组的末尾 :participant
:participants => item.item_participations.map { |item|
{:item_image => item.user.profile_pic.url(:small)}
}
我希望这种情况在室内发生不超过3次。我试着用索引映射,但没用
在循环中最多运行3次后,有没有关于如何中断的建议?您需要对数组进行
切片
,在该集合上执行映射
,然后将数组的其余部分连接到映射
返回的数组的末尾
:participants => (item.item_participations[0..2].map { |item|
{:item_image => item.user.profile_pic.url(:small)}
} + item.item_participations[3..-1])
下面是一个例子:
my_array.take(3).map { |element| calculate_something_from(element) }
从Ruby 1.9开始,您可以使用map.with\u索引:
:participants => item.item_participations.map.with_index { |item, idx|
{:item_image => item.user.profile_pic.url(:small)}
break if i == 2
}
虽然我比较喜欢Justice提出的方法。在哪里定义了
take
方法?take方法是在Enumerable->中定义的,这对我不起作用。。抛出错误:undefined method'with_index'for#
为我的问题找到了解决方案:t('date.day_name')。每个带有_index.map{| day,idx |[day,idx]}的
看起来像是map.with_index在Ruby 1.9之前不可用。