What's a good pattern facade pattern for creating idiomatic Ruby iterators from Java iterators?
I'm using JRuby 1.6.0.RC1. I would like to use the java.util.Iterators
on some Java libraries more idiomatically from Ruby, by providing a facade im开发者_JAVA百科plementing a Ruby each
method.
My first attempt was basically like this:
def each_property( myJavaObj )
i = myJavaObj.myIterator
while i.hasNext
yield i.next
end
end
However, when I call each_property {|p| puts "#{p}"}
I get the error: LocalJumpError: yield called out of block
.
Can anyone either suggest what I'm doing wrong, or point to a better pattern for invoking Java iterators from Ruby?
JRuby has builtin support for turning java.util.Iterator
s into Ruby Enumerable
s. So you might also wish to simply do
myJavaObj.myIterator.each { ... }
in your code.
I'm not sure, but maybe calling yield
inside the while
block causes this issue.
You may try calling the block explicitly:
def each_property(myJavaObj, &block)
i = myJavaObj.myIterator
while i.hasNext
block.call i.next
end
end
精彩评论