Skip to content
Browse files

Fixing Array#choice on 1.9

  • Loading branch information...
1 parent ce2dad4 commit 7632d9343a308cb88d4d1f702e6e2d189b187be3 @steveklabnik committed Oct 10, 2011
Showing with 19 additions and 0 deletions.
  1. +19 −0 kernel/common/array19.rb
View
19 kernel/common/array19.rb
@@ -6,6 +6,25 @@ def self.try_convert(obj)
Rubinius::Type.try_convert obj, Array, :to_ary
end
+ def choice(n=undefined)
+ raise NoMethodError if size == 0
+ return at(Kernel.rand(size)) if n.equal? undefined
+
+ n = Type.coerce_to(n, Fixnum, :to_int)
+ raise ArgumentError, "negative array size" if n < 0
+
+ n = size if n > size
+ result = Array.new(self)
+
+ n.times do |i|
+ r = i + Kernel.rand(size - i)
+ result.tuple.swap(i,r)
+ end
+
+ result[n..size] = []
+ result
+ end
+
def flatten(level=-1)
level = Rubinius::Type.coerce_to(level, Integer, :to_int)
return self.dup if level == 0

0 comments on commit 7632d93

Please sign in to comment.
Something went wrong with that request. Please try again.