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

More than 3 years have passed since last update.

@azyapa

Array(配列)で任意の要素を一番先頭に入れ替える方法

RailsのActiveRecordでテーブルから取り出したデータを並べ換えるのに苦労したのでメモする

ある条件を満たすユーザーだけまとめて取り扱いたい場合

user.controller.rb
@user = User.where(status: 10)

みたいな感じでステータスが10のユーザーだけ取り出す

この時、id順に@userに格納される

pry(main)> @user = User.where(status: 10)
 #<User:0x00000000000
  id: 1,
  email: "email@example.com",
  name: "Test1",
  status: 10,

 #<User:0x00000000000
  id: 2,
  email: "email2@example.com",
  name: "Test2",
  status: 10,

 #<User:0x00000000000
  id: 3,
  email: "email3@example.com",
  name: "Test3",
  status: 10,

 #<User:0x00000000000
  id: 4,
  email: "email4@example.com",
  name: "Test4",
  status: 10,

要は@userの中には
Test1→Test2→Test3→Test4
の順番で要素が入っている

今回はこれを
Test3→Test1→Test2→Test4
にしたい!!!

以下やったこと

①.unshiftメソッドで先頭に挿入する
*参考:https://ref.xaio.jp/ruby/classes/array/unshift

pry(main)> @swap_user = User.find_by(id:3)
.
.
.
pry(main)> @user = User.where(status: 10).unshift(@swap_user)
 #<User:0x00000000000
  id: 3,
  email: "email3@example.com",
  name: "Test3",
  status: 10,

 #<User:0x00000000000
  id: 1,
  email: "email@example.com",
  name: "Test1",
  status: 10,

 #<User:0x00000000000
  id: 2,
  email: "email2@example.com",
  name: "Test2",
  status: 10,

 #<User:0x00000000000
  id: 3,
  email: "email3@example.com",
  name: "Test3",
  status: 10,

 #<User:0x00000000000
  id: 4,
  email: "email4@example.com",
  name: "Test4",
  status: 10,

このままだと1番最初にTest3を挿入しただけになってしまうので、.uniqメソッドを付け足す

Test3→Test1→Test2→Test3→Test4

②.uniqメソッドで被っている要素を削除
*参考:https://ref.xaio.jp/ruby/classes/array/uniq

pry(main)> @user = User.where(status: 10).unshift(@swap_user).uniq
 #<User:0x00000000000
  id: 3,
  email: "email3@example.com",
  name: "Test3",
  status: 10,

 #<User:0x00000000000
  id: 1,
  email: "email@example.com",
  name: "Test1",
  status: 10,

 #<User:0x00000000000
  id: 2,
  email: "email2@example.com",
  name: "Test2",
  status: 10,

 #<User:0x00000000000
  id: 4,
  email: "email4@example.com",
  name: "Test4",
  status: 10,

これで
Test3→Test1→Test2→Test4
になった!!!!

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