我从这个帖子中偷了我的头衔:
Executes a function until it returns a nil,collecting its values into a list
这个问题是指Lisp,坦白说,我的头脑.但是,我认为他的问题 – 被翻译成Ruby – 正是我自己的:
What’s the best way to create a conditional loop in [Ruby] that executes a function until it returns NIL at which time it collects the returned values into a list?
我目前的笨拙方法是:
def foo ret = Array.new x = func() # parenthesis for clarity (I'm not a native Ruby coder...) until x.nil? ret << x x = func() end ret end
解决方法
有趣的是没有人建议
Enumerator
和它的take_while方法,对我来说似乎只是适合:
# example function that sometimes returns nil def func r = rand(5) r == 0 ? nil : r end # wrap function call into lazy enumerator enum = Enumerator.new{|y| loop { y << func() } } # take from it until we bump into a nil arr = enum.take_while{|elem| !elem.nil? } p arr #=>[3,3,2,4,1,1]