LoginSignup
2
0

More than 1 year has passed since last update.

[Rails] Arrayメソッドで使うfirstとlastとそれ以外について

Last updated at Posted at 2021-06-22

環境

ruby 2.6.6
Rails 6.0.3.6

本題

Rubyには配列メソッドとしてfirstlastというものが存在します。

[0,1,2].first
=> 0

[0,1,2].last
=> 1

それぞれ配列の要素の最初と最後を取得するメソッドです。
それに加えてRailsには新たなメソッドsecond,third,fourth,fifthがあります。
※これらはRailsのメソッドであり,Rubyの組込みメソッドではありません。

使い方は以下のようになります

[1,2,3,4,5].second
=> 2

[1,2,3,4,5].third
=> 3

[1,2,3,4,5].fourth
=> 4

[1,2,3,4,5].fifth
=> 5

それぞれ配列の2,3,4,5番目から要素を取得します。

2
0
5

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