Idiomatic Ruby - Execute a function until it returns a nil, collecting its values into a list

Viewed 2874

I stole my title from this post: Executes a function until it returns a nil, collecting its values into a list

That question refers to Lisp and is, frankly, over my head. However, I think that his question--translated into Ruby--is exactly my own:

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?

My current, clunky approach is this:

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

This code snippet will do what I want...but I know there is a cleaner, more idiomatically Ruby approach...right?

5 Answers
Related