0
0

More than 3 years have passed since last update.

each_with_indexの使い方について

Posted at

eachループしつつ、それぞれデータに番号を振り分けて全体で何番目という風な記述にしたい場合に何か良いのがないか探してみたところ
便利なeach_with_indexというメソッドを見つけることができましたのでアウトプットがてら紹介したいと思います。

each_With_indexの使い方

ruby.html.erb
<% @users.each_with_index do |user, i| %>
<%= "#{user}は、 #{i+1}位:" %>
<% end %>
userは(iに1プラスした値)

なおindexは0から始まるため+1にしてますが、初期値の0から始めたい場合は{i}だけで大丈夫です。

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