2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-04-09

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
になった!!!!

2
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?