LoginSignup
5
5

More than 5 years have passed since last update.

Railsのinstance.first とか instance.last はソートもしてくれてしまう。

Posted at

lastとfirstメソッドは実はソートもしてくれていた。

モデルから生成したインスタンスの配列に限りますが、ソートしてくれてます

順番通り並ぶ配列も .last を実行すると逆順ソートになる

[1] @todos.pluck(:name)
=> ["1番目のタスク", "2番目のタスク", "3番目のタスク"]

[2] @todos.last
=> #<id: xxx, name: "3番目のタスク">

[3] @todos.pluck(:name)
=> ["3番目のタスク", "2番目のタスク", "1番目のタスク"]

逆順ソートされた配列も .first をすれば元に戻る

[4] @todos.first
=> #<id: xxx, name: "1番目のタスク">

[5] @todos.pluck(:name)
=> ["1番目のタスク", "2番目のタスク", "3番目のタスク"]

面白いですね。

ちなみに以下のような、普通の配列だとこうなりません

todos = [1, 2, 3]

どうやらソートしてるらしい。

Person.first # returns the first object fetched by SELECT * FROM people ORDER BY people.id LIMIT 1
Person.where(["user_name = ?", user_name]).first
Person.where(["user_name = :u", { u: user_name }]).first
Person.order("created_on DESC").offset(5).first
Person.first(3) # returns the first three objects fetched by SELECT * FROM people ORDER BY people.id LIMIT 3
# File activerecord/lib/active_record/relation/finder_methods.rb, line 118
def first(limit = nil)
  if limit
    find_nth_with_limit(0, limit)
  else
    find_nth 0
  end
end
5
5
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
5
5