开发者

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.Iterators into Ruby Enumerables. 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜