Ruby Method of the Day - Array.delete

Posted by Kelly McCauley on Nov 13, 2007

Signature

array.delete(object)                #=> object or nil
array.delete(object) {|o| block }   #=> object or returned_block_result

array.delete(object) removes all occurances of object from array and returns object if object is found in array or it returns nil if object is not found in array. If block is given and object is not found in array then the the block’s returned results is returned by array.delete.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
a = [1,2,3,4,5,6,7]       #=> [1, 2, 3, 4, 5, 6, 7]
a.delete(7)               #=> 7
a                         #=> [1, 2, 3, 4, 5, 6]
a.delete('foo')           #=> nil

a = [7,1,2,3,7,4,5,6,7]   #=> [7, 1, 2, 3, 7, 4, 5, 6, 7]
a.delete(7)               #=> 7
a                         #=> [1, 2, 3, 4, 5, 6]

a.delete('foo') {false}   #=> false

a.delete('foo') do |item|
  "'#{item}' not found"
end                       #=> "'foo' not found"

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.delete

Trackbacks

Use the following link to trackback from your own site:
http://drotner.org/articles/trackback/69