diff options
author | Giuseppe Bilotta <giuseppe.bilotta@gmail.com> | 2008-04-08 23:54:49 +0200 |
---|---|---|
committer | Giuseppe Bilotta <giuseppe.bilotta@gmail.com> | 2008-04-09 01:30:37 +0200 |
commit | cfc6d31ac24b3c705eaa7302ced01d5f33135dc4 (patch) | |
tree | ad7be2d1d8bd345a7ba170f8e5e7878dc550a675 /lib | |
parent | 55eae6dcf60c8b24452cf5eb75f18aacb3469215 (diff) |
extends: Array#delete_one takes an optional argument for the element to delete: if nil or absent, a random element is returned and deleted
Diffstat (limited to 'lib')
-rw-r--r-- | lib/rbot/core/utils/extends.rb | 16 |
1 files changed, 12 insertions, 4 deletions
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 |