1
1

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 3 years have passed since last update.

配列で便利なメソッドを紹介するぞpart1

Last updated at Posted at 2020-07-07

whereメソッド基本形

User.where(admin: true)

この場合、adminがtrueのユーザーを全て取得することができる。

whereメソッドの配列で指定

User.where(kind: [1,2])

この場合、kindが1、または2のユーザーを全て取得することができる。

where.notメソッド

User.where.not(id: 2)

この場合、idが2のユーザー以外を取得することができる。

whereメソッドで比較

User.where("kind" > "?", 1)

これでkindが1より大きいユーザーを全て取得することができる。

whereメソッドでorを使う

User.where('kind = ? or name = ?', 0, 'yamada')

この場合、kindが0かnameがyamadaのユーザーを全て取得することができる。

whereメソッドでandを使う

User.where('kind = ? and name = ?, 0, "yamada")

この場合、kindが0かつ、nameがyamadaのユーザーを全て取得することができる。

whereメソッドでメソッドチェーンを使う

User.where(kind: 0).where(name: 'yamada')

この場合、意味は先ほどのandと同じになる。

distinct uniqメソッド

これは配列の中で被っている要素をなくすメソッド。

Sample.select(:last_name,:first_name).distinct

# レコード件数を数える場合
Sample.select(:last_name).distinct.size
[1,1,2,2,3,3].distinct

=>[1,2,3]

こんな感じで使う。

uniqメソッドも使えるが、どうやら非推奨らしい。

sampleメソッド

sampleメソッドは配列の中からランダムで要素を取り出すメソッド。

配列.sample
配列.sample(2)

引数がない場合は1つだけ要素を取り出す。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?