LoginSignup
0
1

More than 5 years have passed since last update.

[rails]データをピックアップ!

Last updated at Posted at 2017-06-21

Rails,rubyの配列やactiverecord:relationからのピックアップの仕方まとめ

first

fruits = ["apple", "orange", "banana", "kiwi"]
p fruits.first    #->"apple"
p fruits.first(2) #->["apple", "orange"]

limit(rails)

railsのメソッドですが、User.all.first 2だったらUser.limit 2にできます。

# <モデル.limit(最大取得行数)>
User.limit(5) # SELECT * FROM users LIMIT 5

shuffle,shuffle!

配列をランダムに入れ替えます。shuffle!で破壊的メソッドになります。

fruits = ["apple", "orange", "banana", "kiwi"]
p fruits.shuffle #-> ["banana", "kiwi", "apple", "orange"]

sample(choice)

sampleは配列をランダムにピックアップしてきてくれます。
choiceメソッドはRuby 1.8.7に追加されましたが、Ruby 1.9ではsampleメソッドに変わりました。

animals = ["dog", "cat", "mouse", "rabbit", "horse"]
puts animals.sample #-> cat
p animals.sample(2) #-> ["horse", "mouse"]
0
1
1

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