]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/commitdiff
extends: updated shuffle method
authorJay Thomas <degradinglight@gmail.com>
Thu, 25 Apr 2013 03:01:56 +0000 (23:01 -0400)
committerGiuseppe Bilotta <giuseppe.bilotta@gmail.com>
Thu, 25 Apr 2013 04:44:18 +0000 (06:44 +0200)
lib/rbot/core/utils/extends.rb

index 208cb089a41b63fac593eaec6cbbc65093989ead..f36623951ad32ced31d7080091e7da6770ebe369 100644 (file)
@@ -119,22 +119,22 @@ class ::Array
     end
   end
 
+  # Taken from Ruby backports:
   # shuffle and shuffle! are defined in Ruby >= 1.8.7
 
-  # This method returns a new array with the same items as
-  # the receiver, but shuffled
-  unless method_defined? :shuffle
-    def shuffle
-      sort_by { rand }
-    end
-  end
+  # This method returns a new array with the
+  # same items as the receiver, but shuffled
+  def shuffle
+    dup.shuffle!
+  end unless method_defined? :shuffle
 
-  # This method shuffles the items in the array
-  unless method_defined? :shuffle!
-    def shuffle!
-      replace shuffle
+  def shuffle!
+    size.times do |i|
+      r = i + Kernel.rand(size - i)
+      self[i], self[r] = self[r], self[i]
     end
-  end
+    self
+  end unless method_defined? :shuffle!
 end
 
 module ::Enumerable