LoginSignup
0
0

More than 5 years have passed since last update.

配列の要素2つごとに線を引いて表示させる方法

Last updated at Posted at 2018-10-11

この記事では、初心者向けに配列の要素を下記のように表示させるロジックを紹介したいと思います。
実行環境は、Ruby2.3.1 Rails5.2.1 です。

96839ab1756c575a1204ae3b80818a25.png

重複なくデータを表示させるためのRubyの便利なeach_with_indexメソッドを紹介させていただきます。

each_with_indexメソッドの書き方


配列.each_with_index do |item, i|

具体的なソースコード


games=[“将棋”, “囲碁”, “オセロ”]

#配列gamesを用意

games.each_with_index do |item, i|

puts “#{i+1}番目の要素は#{item}です。”

end


結果

1番目の要素は将棋です。

2番目の要素は囲碁です。

3番目の要素はオセロです。

次にループの処理が2回行われるごとに線を引きます。


<% @post.each_with_index do |post, i| %>

  <% if i%2==0 %>
    <hr>

    <%= post.id %>

  <% else %>
    <div clasa = "content2">
    <%= post.id %>
    </div>
  <% end %>

<% end %>

これで下記のとおり、データ2つごとに線を引く動作が出来ます。

a6e6402637c740f6e9a663db66532f06.png

あとは、データベースから画像を受け取ったり、レイアウトを調整すれば、下記のようなものが創れます。
8d27b2d1faef85495ae44be47df8c320.png

以上です。

0
0
1

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
0
0