Hello all, here's a little convenience library we whipped up a couple weeks back with Christian Neukirchen. It's very simple, but we hope someone might find it useful
···
---
rand.rb is a library for picking random elements and shuffling.
This work is licensed under the same terms as Ruby itself.
Overview
rand.rb adds new methods to Enumerable, Array, and Hash to:
* return a random element (pick, pick_index, pick_key, pick_value and their destructive versions suffixed with !).
* arrange elements in new, random order (shuffle, shuffle_hash_pairs, shuffle_hash).
* use above methods in convenient ways (each_random, map_random).
It also provides these new facilities to String:
* shuffle_chars, to arrange the characters of the string in new order.
* pick_byte, pick_char and pick_index, to return random bytes, characters or elements.
Examples:
arr = (1..10).to_a
arr.pick # => 3
arr.pick # => 7
arr.shuffle # => [3,5,2,10,8,7,6,1,9,4]
str = "string strung strong rang"
str.pick_char # => 'n'
str.pick_byte # => 97
str.shuffle_chars # => "srsntnignrgrgttsuan r og"
hash = {'a'=>2, 'b'=>3, 'c'=>4}
hash.pick! #=> ['c', 4]
hash #=> {'a'=>2, 'b'=>3}
hash.pick_key #=> 'b'
hash.pick_value #=> 2
File.open("foo"){|f|
f.each_random{|line| puts line } # about equal to readlines.shuffle.each{...}
}
History
* November 26, 2004: Initial version done as IRC collaboration project between kig and chris2.
* November 29, 2004: First public release 0.9.
Getting it
rand.rb is packaged in RPA.
rpa install rand
You can download rand.rb at:
http://kronavita.de/chris/data/rand-0.9.0.tar.gz
Upstream source:
You can get latest development releases using darcs by executing:
darcs get http://kronavita.de/chris/data/rand
darcs send is the preferred way to send patches, but mailing diffs is fine too.
Authors
* Ilmari Heikkinen: Code and unit tests
* Christian Neukirchen: Documentation and housekeeping.
Please mail bugs, feature requests or patches to the mail addresses above or use IRC to contact the developers.
Copyright
Copyright 2004 Ilmari Heikkinen < kig misfiring net >
Parts Copyright 2004 Christian Neukirchen < chneukirchen gmail com >
P.S. I guess it's bad mojo to start versions from 0.9, but it _is_ very simple