惯用Ruby – 执行一个函数,直到它返回一个零,收集它的值到列表中

我从这个帖子中偷了我的头衔: 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]

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...