Forum: Ruby-dev [ruby-trunk - Feature #4147] Array#sample で重みを指定したい

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
C4e88907313843cf07f6d85ba8162120?d=identicon&s=25 yhara (Yutaka HARA) (Guest)
on 2012-10-25 16:53
(Received via mailing list)
Issue #4147 has been updated by yhara (Yutaka HARA).

Target version changed from 2.0.0 to next minor

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

Author: oj (Yoji Ojima)
Status: Assigned
Priority: Normal
Assignee: shyouhei (Shyouhei Urabe)
Target version: next minor

 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]
This topic is locked and can not be replied to.