Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@rorensu2236

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

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
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
5
Help us understand the problem. What are the problem?