概要
Array#sample
詳細
配列の要素を1つランダムに返却。配列が空の場合はnilを返却。
引数を指定した場合は、任意の数をランダムに抽出する。
サンプルコード
# encoding: utf-8 ary = %w[1 2 3 4 5] 10.times {print ary.sample} puts puts "--------------" 10.times {print ary.sample(2)} puts puts "--------------" ary = Array.new print ary.sample.nil?
出力
2553134212 -------------- ["2", "4"]["5", "2"]["3", "2"]["3", "1"]["1", "3"]["3", "4"]["5", "1"]["1", "5"]["4", "2"]["3", "4"] -------------- true