Ruby Tips!

RubyのTipsを紹介します

配列の要素をランダムに取得する

Ruby 1.8.6以前では配列の要素をランダムに取得するメソッドは存在しない。
Array#lengthrandを使って以下のようにする。

a = [1, 2, 3, 4, 5]
p a[rand(a.length)] #=> 2

Ruby 1.8.7Ruby1.9.0ではArray#choiceが利用できる。

a = [1, 2, 3, 4, 5]
a.choice #=> 4

Ruby 1.9.1以降ではArray#choiceは廃止された。
代わりにArray#sampleを使う。

a = [1, 2, 3, 4, 5]
a.sample #=> 3