微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

惯用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]

原文地址:https://www.jb51.cc/ruby/272671.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐