Clean way to print error & break from loop?

I would like an idiomatic way to print an error from inside of a loop
and break from that loop in a single statement. I thought I could do
something simple with “and” but it doesn’t work with Kernel#puts due to
#puts returning nil.

e.g.
loop do
rc = do_some_work

STDERR.puts “Work failed” and break unless ok?(rc)
end

I can get that example to work if I use “or” for flow control rather
than “and” but it doesn’t read right to me.

STDERR.puts “Work failed” or break unless ok?(rc) # yuck

Any suggestions for a nice, clean, idiomatic way of accomplishing the
above?

cr

Use a regular multiline if.

Or, if you’re feeling like golfin’:

break puts 'whatevs' unless ok?(rc)

Break can take an argument, and it will be the value returned by loop.

– Matma R.

On Oct 14, 2011, at 3:01 PM, Bartosz Dziewoński wrote:

Use a regular multiline if.

Or, if you’re feeling like golfin’:

break puts ‘whatevs’ unless ok?(rc)

Break can take an argument, and it will be the value returned by loop.

I like that second solution. Thanks!

cr

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs