加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:06:43 所属栏目:百科 来源:网络整理
导读:我从这个帖子中偷了我的头衔: 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 l
我从这个帖子中偷了我的头衔: 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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读