Created
August 8, 2013 09:04
-
-
Save cantin/6182978 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
class Iterator < Enumerator | |
def initialize obj, meth, *args | |
super() do |y| | |
loop do | |
y << obj | |
obj = obj.send(meth, *args) | |
end | |
end | |
end | |
end | |
class Object | |
def iter_for meth, *args | |
Iterator.new self, meth, *args | |
end | |
alias :to_iter :iter_for | |
end |
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_relative 'to_iter' | |
# Note: this conflicts with Object#to_iter | |
class Method | |
def to_iter *args | |
Iterator.new receiver, name, *args | |
end | |
end |
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 'test/unit' | |
require './iter_for.rb' | |
class IterForTest < Test::Unit::TestCase | |
def test_iter_for | |
# Test on Integer#next => Integer | |
assert_equal([0, 1, 2, 3, 4], 0.iter_for(:next).take(5)) | |
# Test on String#succ => String | |
assert_equal(%w[a b c d e f g h i j], 'a'.iter_for(:succ).take(10)) | |
# Test on Integer#inspect => String#inspect => String | |
assert_equal([1, "1", "\"1\""], 1.iter_for(:inspect).take(3)) | |
end | |
def test_iter_for_args | |
# Test with a parameter | |
assert_equal([0, 2, 4, 6, 8], 0.iter_for(:+, 2).take(5)) | |
end | |
end |
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 'test/unit' | |
require './method_to_iter.rb' | |
class MethodToIterTest < Test::Unit::TestCase | |
def test_to_iter | |
# Test on Integer#next => Integer | |
assert_equal([0, 1, 2, 3, 4], 0.method(:next).to_iter.take(5)) | |
# Test on String#succ => String | |
assert_equal(%w[a b c d e f g h i j], 'a'.method(:succ).to_iter.take(10)) | |
# Test on Integer#inspect => String#inspect => String | |
assert_equal([1, "1", "\"1\""], 1.method(:inspect).to_iter.take(3)) | |
end | |
def test_iter_for_args | |
# Test with a parameter | |
assert_equal([0, 2, 4, 6, 8], 0.method(:+).to_iter(2).take(5)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment