title: How do I do early return in ruby to reduce nested if?
body: <p>I always use early return to reduce nested if (programing with other languages) like this:</p>
  
  <pre class="lang-c prettyprint-override"><code>//instead of nested if like this 
  if (condition1) {
     if (condition2) {
       if (condition3) {
         //... finally meet all conditions 
         //do the job 
       }
     }
  }
  //return early 
  if (!condition1) {
     //clean up resource in step #1
     return
  }
  if (!condition2) {
     //clean up resource in step #2
     return
  }
  if (!condition3) {
     //clean up resource in step #2
     return
  }
  ...
  //finally meet all conditions 
  </code></pre>
  
  <p>But how do I do early return in ruby ? I can't return inside a if block in Ruby. I got the error </p>
  
  <blockquote>
    <p>"Uncaught exception: unexpected return ... `block (2 levels) in ': unexpected return (LocalJumpError)"</p>
  </blockquote>
  
  <p>---- update -----</p>
  
  <p>Sorry I forgot to mention that in a simple situation like this it works</p>
  
  <pre><code>def early(input)
    if (input &lt;0)
      puts 'should &gt;0'
      return
    end
    puts 'good'
  end
  </code></pre>
  
  <p>I am learning Fiber and I use the sample from <a href="https://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/" rel="nofollow noreferrer">https://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/</a></p>
  
  <pre><code>def http_get(url)
    f = Fiber.current
    http = EventMachine::HttpRequest.new(url).get
  
    # resume fiber once http call is done
    http.callback { f.resume(1,http) }
    http.errback  { f.resume(2,http) }
  
    return Fiber.yield
  end
  
  EventMachine.run do
    Fiber.new{
      result = http_get('https://www.google.com/')
      if (result[0] ==2) 
        puts "error"
        return # using break has the error 'break from proc-closure (LocalJumpError)' too 
      end
      result = http_get('https://www.google.com/search?q=eventmachine')
      page = result[1]
      puts "Fetched page 2: #{page.response}"
    }.resume
  end
  </code></pre>
  
  <p>I got the error.</p>
  
  <p>---- update 2 ----</p>
  
  <p>With the answer and comments I got I found this <a href="https://stackoverflow.com/questions/2518075/how-can-i-return-something-early-from-a-block">How can I return something early from a block?</a> </p>
  
  <p>And this <a href="https://stackoverflow.com/questions/8888958/why-does-the-break-statement-in-ruby-behave-differently-when-using-proc-new-v-t">Why does the break statement in ruby behave differently when using Proc.new v. the ampersand sign?</a> explains why break won't work either. To quote "break is supposed to make the caller of the block return, but Proc.new has already returned."</p>
  
  <p>return vs break vs next is definitely an obstacle for a ruby newbie </p>