Skip to content

Commit

Permalink
Function array_diff now compared to using the "-" operator on arrays.
Browse files Browse the repository at this point in the history
  • Loading branch information
Maurice Machado committed Dec 17, 2009
1 parent 16d1dc5 commit f0778c4
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions array/array_diff.markdown
Original file line number Diff line number Diff line change
@@ -1,27 +1,42 @@
# array_diff

We can find the difference between two arrays using the `Enumerable#reject`
method. This method rebuilds an array based on conditions that are evaluated
in a block. In the block we simply reject any element of the array that is in
the comparison array.
In Ruby, many operators are implemented as methods, and you can even redefine them.

{{code:php
$animals1 = array('cat', 'dog', 'bat', 'rat');
$animals2 = array('cat', 'dog');
$animals2 = array('bat', 'rat');

$result = array_diff($animals1, $animals2);
var_export($result);
// => array(2 => 'bat', 3 => 'rat')
// => array(0 => 'cat', 1 => 'dog')
}}

{{code:ruby
animals1 = ['cat', 'dog', 'bat', 'rat']
animals2 = ['cat', 'dog']
['cat', 'dog', 'bat', 'rat'] - ['bat', 'rat']
# => ["cat", "dog"]
}}

That is equivalent to calling:

p animals1.reject {|a| animals2.include?(a) }
# => ["bat", "rat"]
{{code:ruby
['cat', 'dog', 'bat', 'rat'].-(['bat', 'rat'])
# => ["cat", "dog"]
}}

If you don't quite agree with Ruby on how exclusions should be handled, Ruby lets you have it your way:

{{code:ruby
def Array
def - other
self.each_with_index do |item, i|
self[i] += '-blacklisted' if other.include? item
end
end
end

['cat', 'dog', 'bat', 'rat'] - ['bat', 'rat']
# => ["cat", "dog", "bat-blacklisted", "rat-blacklisted"]
}}

{{related:
array/array_diff_assoc
Expand Down

0 comments on commit f0778c4

Please sign in to comment.