Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class FilterableEnumerable
def initialize(original)
@original = original
end
def >(value)
@original.select { |v| v > value }
end
def >=(value)
@original.select { |v| v >= value }
end
def <(value)
@original.select { |v| v < value }
end
def <=(value)
@original.select { |v| v <= value }
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 >(value)
select { |v| v > value }
end
def <(value)
select { |v| v < value }
end
def filter
FilterableEnumerable.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_neq
assert_equal [0, 1, 2, 3, 4, 6, 7, 8, 10], @array.filter != 5
end
def test_method_missing
assert_equal [0], @array.filter.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