2
3

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.

RubyのArrayをorder by rand

Posted at

order by randと言ったらSQLでたまに話題にあがりますが、それとは関係なく、RubyのArrayをランダムに並び替え(シャッフル)たくなったので、自分用にコードを残しときます。
Fisher-Yatesアルゴリズムのつもりで書いてます。

改善点等ありましたらバシバシご指摘お願いします。

order_by_rand.rb
class Array
  def order_by_rand
    n = self.size
    n.times do |i|
      idx = rand(n-i)
      self[idx], self[-(i+1)] = self[-(i+1)],self[idx]
    end
    self
  end
end
2
3
3

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?