Project

General

Profile

Actions

Feature #5584

closed

Array#sample!

Added by Glass_saga (Masaki Matsushita) over 12 years ago. Updated about 12 years ago.

Status:
Rejected
Assignee:
-
Target version:
[ruby-dev:44817]

Description

=begin
ランダムに選択した要素をレシーバから取り除いて返すメソッドArray#sample!の追加を提案します。

配列からランダムに要素を取り出したい場合には

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

などと書く必要がありましたが、Array#sample!があれば

a = (1..5).to_a
a.sample! #=> 4
p a #=> [1, 2, 3, 5]

と簡潔に書く事ができます。

引数を指定した場合は、その数だけレシーバから要素を取り除き、新たな配列に取り除いた要素を入れて返します。

a = (1..10).to_a
p a.sample!(5) #=> [5, 4, 2, 6, 7]
p a #=> [1, 3, 8, 9, 10]

レシーバから選択した要素を取り去ってしまう事以外は、Array#sampleと同じ動作をします。

[].sample! #=> nil
[].sample!(1) #=> []
[1,2,3].sample!(random: rand) #=> 2

patchを添付します。
=end


Files

patch.diff (3 KB) patch.diff Glass_saga (Masaki Matsushita), 11/07/2011 03:43 PM
by_sorah.diff (5.3 KB) by_sorah.diff sorah (Sorah Fukumori), 11/08/2011 11:37 PM
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0