Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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
basicinc
マーケティングとテクノロジーで社会のあらゆる問題を解決する集団
https://tech.basicinc.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした