Skip to content

Instantly share code, notes, and snippets.

@technicalpickles
Forked from jqr/snippet.rb
Created April 6, 2009 03:17
Show Gist options
  • Save technicalpickles/90627 to your computer and use it in GitHub Desktop.
Save technicalpickles/90627 to your computer and use it in GitHub Desktop.
class FilterableEnumerable
def initialize(original)
@original = original
end
def ==(value)
@original.select { |v| v == value }
end
def method_missing(sym, *args, &block)
@original.select {|v| v.send(sym, *args, &block) }
end
def respond_to?(sym, include_private = false)
@original.all? {|v| v.respond_to?(sym, include_private) }
end
end
class NegativeFilterableEnumerable
def initialize(original)
@original = original
end
def ==(value)
@original.select { |v| v != value }
end
def method_missing(sym, *args, &block)
@original.select {|v| ! v.send(sym, *args, &block) }
end
def respond_to?(sym, include_private = false)
@original.all? {|v| v.respond_to?(sym, include_private) }
end
end
module Enumerable
def filter
FilterableEnumerable.new(self)
end
def filter_not
NegativeFilterableEnumerable.new(self)
end
end
require 'test/unit'
class TestFilterableEnumerable < Test::Unit::TestCase
def setup
@array = (0..10).to_a
end
def test_gte
assert_equal [5, 6, 7, 8, 9, 10], @array.filter >= 5
end
def test_gt
assert_equal [6, 7, 8, 9, 10], @array.filter > 5
end
def test_lte
assert_equal [0, 1, 2, 3, 4], @array.filter < 5
end
def test_le
assert_equal [0, 1, 2, 3, 4, 5], @array.filter <= 5
end
def test_eq
assert_equal [5], @array.filter == 5
end
def test_not_eq
assert_equal [0, 1, 2, 3, 4, 6, 7, 8, 9, 10], @array.filter_not == 5
end
def test_method_missing
assert_equal [0], @array.filter.zero?
end
def test_not_method_missing
assert_equal [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], @array.filter_not.zero?
end
def test_respond_to
assert @array.filter.respond_to?(:zero?)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment