From cfc6d31ac24b3c705eaa7302ced01d5f33135dc4 Mon Sep 17 00:00:00 2001 From: Giuseppe Bilotta Date: Tue, 8 Apr 2008 23:54:49 +0200 Subject: extends: Array#delete_one takes an optional argument for the element to delete: if nil or absent, a random element is returned and deleted --- lib/rbot/core/utils/extends.rb | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/rbot/core/utils/extends.rb b/lib/rbot/core/utils/extends.rb index e9581bc0..f3861745 100644 --- a/lib/rbot/core/utils/extends.rb +++ b/lib/rbot/core/utils/extends.rb @@ -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 -- cgit v1.2.3