如何在 Ruby 中的 do 循环中显示特定范围?

How to display specific range in do loop in Ruby?

我无法在 Ruby 的 do-loop 中显示特定范围的数据。 我有这个示例代码:

Post

<!-- Display loop only 9 sections -->
<div class="row">
<% @post.each do |post| %>
    <div clas="blog">
        <h3 class="heading"><%= post.title %></h3>
    </div>
</div>
<!-- END => Display loop only 9 sections -->

<div class="row">
    <div clas="banner">
        <img src="images/banner.jpg" alt="banner">
    </div>
</div>

<!-- Continue display loop for 10 and until latest sections -->
<div class="row">
<% @post.each do |post| %>
    <div clas="blog">
        <h3 class="heading"><%= post.title %></h3>
    </div>
</div>
<!-- END => -->

在这种情况下,我想在显示 9 posts 后添加一个横幅部分:

<div class="row">
    <% @post.each do |post| %>
        <div clas="blog">
            <h3 class="heading"><%= post.title %></h3>
        </div>
    </div>
    <!-- END => Display loop only 9 sections -->

<!-- I will add this banner section after posts displays 9 posts -->
<div class="row">
        <div clas="banner">
            <img src="images/banner.jpg" alt="banner">
        </div>
    </div>

然后我想在添加横幅部分后从 post 10 到最近的 post 继续显示 post:

<!-- Continue display loop for 10 and until latest sections -->
<div class="row">
<% @post.each do |post| %>
    <div clas="blog">
        <h3 class="heading"><%= post.title %></h3>
    </div>
</div>
<!-- END => -->

在我的情况下,两个 post 部分将显示 post 中的所有数据。怎么在1stdiv元素里限制9post,在3rddiv元素下面继续最新的posts横幅部分使用 do 循环?我想在第 3 部分继续最新的 post。

有什么简单的方法吗?

我目前是 rails 应用程序的新手,我仍在探索该程序的语法。

前 9 个帖子:

<% @post.limit(9).each do |post| %>

横幅下方的其他帖子:

<% @post.drop(9).each do |post| %>

也许:

<% @post[0..8].each do |post| %>
...
<% @post[9..-1].each do |post| %>

或:

BANNER_POSITION = 9
<% @post[0...BANNER_POSITION].each do |post| %>
...
<% @post[BANNER_POSITION..-1].each do |post| %>

您可以使用 .each_with_index 方法来确定集合中的这个确切元素是否为第 9 个,这里是文档 link:https://ruby-doc.org/core-2.7.1/Enumerable.html#method-i-each_with_index

<!-- Display loop only 9 sections -->
<div class="row">
<% @post.each_with_index do |post, index| %>
    <div clas="blog">
        <h3 class="heading"><%= post.title %></h3>
    </div>
</div>

  <% if index == 8 %>
    <div class="row">
      <div clas="banner">
        <img src="images/banner.jpg" alt="banner">
      </div>
    </div>
  <% end %>
<% end %>

像这样的东西应该可以工作