]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/commitdiff
extends: Array#delete_one takes an optional argument for the element to delete: if...
authorGiuseppe Bilotta <giuseppe.bilotta@gmail.com>
Tue, 8 Apr 2008 21:54:49 +0000 (23:54 +0200)
committerGiuseppe Bilotta <giuseppe.bilotta@gmail.com>
Tue, 8 Apr 2008 23:30:37 +0000 (01:30 +0200)
lib/rbot/core/utils/extends.rb

index e9581bc0902a466039ce443003a31c0b7199d957..f3861745442035ebb60e926b61188ec3c0d5aec8 100644 (file)
@@ -94,12 +94,20 @@ class ::Array
     self[rand(self.length)]
   end
 
-  # This method returns a random element from the array, deleting it from the
-  # array itself. The method returns nil if the array is empty
+  # This method returns a given element from the array, deleting it from the
+  # array itself. The method returns nil if the element couldn't be found.
   #
-  def delete_one
+  # If nil is specified, a random element is returned and deleted.
+  #
+  def delete_one(val=nil)
     return nil if self.empty?
-    self.delete_at(rand(self.length))
+    if val.nil?
+      index = rand(self.length)
+    else
+      index = self.index(val)
+      return nil unless index
+    end
+    self.delete_at(index)
   end
 end