Skip to content

Instantly share code, notes, and snippets.

@jerodsanto
Created May 20, 2012 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jerodsanto/2759931 to your computer and use it in GitHub Desktop.
Save jerodsanto/2759931 to your computer and use it in GitHub Desktop.
require "minitest/autorun"
module Enumerable
def collect(&block)
each_with_object([]) { |i, obj| obj << block.call(i) }
end
def detect(&block)
# each_with_object(nil) { |i, obj| obj ||= block.call(i) ? i : nil }
inject(nil) { |obj, i| obj ||= block.call(i) ? i : nil; obj }
end
def select(&block)
each_with_object([]) { |i, obj| obj << i if block.call(i) }
end
def reject(&block)
each_with_object([]) { |i, obj| obj << i unless block.call(i) }
end
end
class StarEctTest < MiniTest::Unit::TestCase
def setup
@array = [1, 2, 3, 4, 5]
end
def test_collect
assert_equal [2, 4, 6, 8, 10], @array.collect { |i| i * 2 }
end
def test_detect
assert_equal 3, @array.detect { |i| i > 2 }
assert_nil @array.detect { |i| i < 0 }
end
def test_select
assert_equal [1, 2], @array.select { |i| i < 3 }
assert_equal [], @array.select { |i| i < 0 }
end
def test_reject
assert_equal [3, 4, 5], @array.reject { |i| i < 3 }
assert_equal [], @array.reject { |i| i > 0 }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment