在 Rails 中排除第一个(或最后一个)“每个" [英] Exclude first (or last) in Rails "each"

查看:46
本文介绍了在 Rails 中排除第一个(或最后一个)“每个"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何排除 Rails 中的第一个和/或最后一个项目:

How do I exclude the first and/or last item in the Rails each:

<% @shops.each_with_index do |shop, i| %>
  ... some code ...
<% end %>

推荐答案

在调用 each_with_index 之前使用范围对数组进行切片:

Use a range to slice the array before invoking each_with_index:

如果要排除第一个元素,从1开始.

If you want to exclude the first element, start from 1.

要排除最后一个元素,请以 -2 结尾.

To exclude the last element, end at -2.

@shops[1..-2].each_with_index do |shop, i| 
   ...
end

这篇关于在 Rails 中排除第一个(或最后一个)“每个"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆