Created
May 20, 2012 23:40
-
-
Save jerodsanto/2759931 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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