Project

General

Profile

Actions

Feature #4147

closed

Array#sample で重みを指定したい

Added by oj (Yoji Ojima) almost 14 years ago. Updated about 8 years ago.

Status:
Feedback
Assignee:
-
Target version:
-
[ruby-dev:42735]

Description

=begin
Array#sample にブロックを渡したとき、ブロックの戻り値を要素の重みとして使用するのはいかがでしょうか。

下記のサンプルで、"大吉" が "凶" の 1000 倍の確率で選択されるようにしたいです。

omikuji_box = [
{:name => "大吉", :weight => 1000},
{:name => "中吉", :weight => 100},
{:name => "小吉", :weight => 10},
{:name => "凶", :weight => 1}
]
omikuji = omikuji_box.sample {|v| v[:weight] }
puts omikuji[:name]
=end


Related issues 1 (0 open1 closed)

Related to Ruby master - Feature #4247: New features for Array#sample, Array#choiceRejectedActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0