I have been trying to find a way to abandon a block and have it evaluate to a specified value. E.g. replace “return” with something else in the following so that it prints 2. I haven’t been able to find anything so far though.

def foo(&block)
  return yield + 1
end
def bar
  return foo{ return 1 }
end
p bar

When I first started with ruby i misunderstood return in blocks and assumed that block were just anonymous methods and that return would return control to the caller of the block. After some painful debugging I found out that it wasn’t the case and now find myself cluttering blocks with control structures instead. From what I can find it doesn’t appear to be possible, I’m not sure why.

1 Response to “return in the middle of a block”

  1. Lokorin Says:

    It does appear to be possible using next.

    def foo(&block)
      return yield + 1
    end
    def bar
      return foo{ next 1; p 'a' }
    end
    p bar
    

    Prints ‘2’ without printing ‘a’.

Sorry, comments are closed for this article.