public
Last active

Defines Object#iter_for(method), which is like #enum_for but lets you encapsulate any method, not just a yielder. https://bugs.ruby-lang.org/issues/8506

  • Download Gist
iter_for.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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
method_to_iter.rb
Ruby
1 2 3 4 5 6 7 8
require_relative 'to_iter'
 
# Note: this conflicts with Object#to_iter
class Method
def to_iter *args
Iterator.new receiver, name, *args
end
end
test_iter_for.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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
test_method_to_iter.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.