Skip to content
This repository

Enumerable#except #133

Closed
wants to merge 1 commit into from

2 participants

Burke Libbey Aaron Patterson
Burke Libbey

I realize there are plenty of good reasons not to further pollute Enumerable, but I get a lot of use out of this method, and I think other people would find it handy as well.

Aaron Patterson
Owner
irb(main):001:0> [1,2,3,4,5] - [2,4]
=> [1, 3, 5]
irb(main):002:0> 
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Showing 1 unique commit by 1 author.

Dec 13, 2010
Burke Libbey Added Enumerable#except ad3178a
This page is out of date. Refresh to see the latest.
10 activesupport/lib/active_support/core_ext/enumerable.rb
@@ -104,6 +104,16 @@ def many?(&block)
104 104 def exclude?(object)
105 105 !include?(object)
106 106 end
  107 +
  108 + # Return a version of the collection with the provided elements removed. Similar to subtracting an array.
  109 + #
  110 + # [1,2,3,4,5].except(2,4)
  111 + # => [1,3,5]
  112 + #
  113 + def except(*exclusions)
  114 + reject { |e| exclusions.include?(e) }
  115 + end
  116 +
107 117 end
108 118
109 119 class Range #:nodoc:
7 activesupport/test/core_ext/enumerable_test.rb
@@ -94,4 +94,11 @@ def test_exclude?
94 94 assert [ 1 ].exclude?(2)
95 95 assert ![ 1 ].exclude?(1)
96 96 end
  97 +
  98 + def test_except
  99 + assert_equal([1, 2, 3, 4, 5].except(2, 4), [1, 3, 5])
  100 + assert_equal([:a, :b, :c].except(:a), [:b, :c])
  101 + assert_equal([:a, :b, :c].except(nil), [:a, :b, :c])
  102 + end
  103 +
97 104 end

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.