Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4615

Break out of a begin/end block early

$
0
0

I want a way to exit a begin/end block while still assigning the variable that its result is assigned to.

def foo  @foo ||= begin    puts "running"    return "leaving early" if true # would be some sort of calculation    # Other calculations  endend

What I hope to happen

> foorunning=> leaving early> foo=> leaving early

What actually happens

> foorunning=> leaving early> foorunning=> leaving early

The code doesn't work because return exits the entire method without setting @foo. Using break or next only work in loops. Does anything work within a begin block the way I'm thinking?

Current ways I can do it but was hoping to avoid:

  • Assigning the variable within the begin block and returning
  • Putting the remaining portion of the begin block in an if statement
  • Performing the calculation before the begin block

There seem to be a lot of related questions about breaking out of blocks but I couldn't find one that answers this specific version (maybe because it's not possible).


Viewing all articles
Browse latest Browse all 4615

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>