我从这篇文章中窃取了我的标题: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
此代码片段将执行我想要的...但我知道有一种更简洁、更惯用的 Ruby 方法...对吧?
最佳答案
有趣的是没有人建议 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]
关于ruby - 惯用的 Ruby - 执行一个函数直到它返回一个 nil,将它的值收集到一个列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6886770/