LoginSignup
8
6

More than 3 years have passed since last update.

each_sliceメソッドの使い方

Last updated at Posted at 2018-10-12

この記事では、Rubyのeach_sliceメソッドを用いて、配列をある要素ごとに分割する方法を紹介します。

配列を要素ごとに2分割する方法について

posts_controller.rb

class PostsController < ApplicationController
  def index
    @posts = ["post1", "post2","post3","post4", ... ,"post10"]
  end
end
index.html.erb
<% @post.each_slice(2) do |post1,post2| %>

    <hr>
     <%= post1.id %>
    <div class = "content">
     <%= post2.id %>
    </div>

<% end %>

上記のコードにより、下記のようになります。

b724f33af51cdcc8bffb43acfc973ac3.png

配列の要素ごとに3分割する方法について

index.html.erb
<% @posts.each_slice(3) do |post1,post2,post3| %>
    <hr>
    <%= post1.id %>
    <%= post2.id %>
    <%= post3.id %>
<% end %>

しかし、上記のように実行すると、ブラウザには下の画像の通り、NoMethodエラーが起きてしまいます。

c95c83f1dbe64d6128c9eb00ec2c8d40.png

エラー画面の<%= post2.id %> のところにnilが入っていますと書かれています。
その原因として、each.slice(3)の場合、ブロック引数に示したpost1,post2,post3に@postから受け取った数字が1ループあたり3つずつ入ります。10は3では割り切れないため、最後のブロック引数の値の2つがnilとなってしまいます。

| 1,2,3 | 4,5,6 | 7,8,9 | 10,nil, nil | となり、引数にnilが含まれていたのでエラーが起きてしまいました。

そこで下記のコードのように、各要素に <% if post(x) != nil%>を付け加えます。
このようにすることで、引数にnilが入った場合は実行しないという動作を実現できます。

index.html.erb
<% @posts.each_slice(3) do |post1,post2,post3| %>
    <hr>

    <% if post1 != nil%>
      <%= post1.id %>
    <% end %>

    <% if post2 != nil %>
      <%= post2.id %>
    <% end %>

    <% if post3 != nil%>
      <%= post3.id %>
    <% end %>
<% end %>

ブラウザでの動作は下の画像の通りになります。

5a7e2623db86fac9f54727889b30e99f.png

まとめ

この記事では、配列を要素ごとに分割するRubyの便利なメソッドについて紹介しました。
参考になれば、幸いです。

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6