ruby - 惯用的 Ruby - 执行一个函数直到它返回一个 nil,将它的值收集到一个列表中

标签 ruby list while-loop return-value null

我从这篇文章中窃取了我的标题: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/

相关文章:

ruby-on-rails - 如何将大的 rspec 文件分成更小的部分

ruby - 如何在 Ruby 中添加数组?

Ruby:防止 cucumber 冗余的方法?

python - 检查列表内多个列表中的项目

java - 继续或中断在三元运算符中不起作用

ruby-on-rails - 你会如何用 Ruby 设计这样的 DSL?

python - 如何从多个列表中找到最大值?

Java - 创建长度递增的字符串列表的时间复杂度

java - 在 while 循环中使用扫描仪时,如何 "prime"循环并创建哨兵?

json - bash:JSON 文件中转义引号的精确再现