In most programming languages that have control-flow keywords, each control-flow keyword has one clear and unambiguous meaning. And then there's Ruby, in which the meaning of return
is contextual: it does two very different things depending on whether or not you're inside of some (but not all!) types of anonymous functions. I'm not familiar with any other language with similar semantics.
That being true, if I have some Ruby code that's reasonably well written, and I want to translate it into another language, (let's say C#, because it's pretty popular around here,) how would I handle the "special" returns in order to preserve the original behavior?
The closest thing I can think of is to turn a "special" return into a throw new RubyNestedReturnException(<return value here>)
and put all invocations in a try/catch
block that catches RubyNestedReturnException
and returns the value inside. This would probably work, but it would be very messy. Is there any better way to do it? (And no, "just turn all invocations that use a proc with "special" returns into a return
statement" is not a good answer, since some invocations involve a proc that gets passed in as an argument from outside the function that invokes them.)