Using 'return' in a Ruby block

后端 未结 7 848
太阳男子
太阳男子 2020-11-28 03:54

I\'m trying to use Ruby 1.9.1 for an embedded scripting language, so that \"end-user\" code gets written in a Ruby block. One issue with this is that I\'d like the users to

7条回答
  •  忘掉有多难
    2020-11-28 04:17

    I believe this is the correct answer, despite the drawbacks:

    def return_wrap(&block)
      Thread.new { return yield }.join
    rescue LocalJumpError => ex
      ex.exit_value
    end
    
    def thing(*args, &block)
      value = return_wrap(&block)
      puts "value=#{value}"
    end
    
    thing {
      return 6 * 7
    }
    

    This hack allows users to use return in their procs without consequences, self is preserved, etc.

    The advantage of using Thread here is that in some cases you won't get the LocalJumpError - and the return will happen in the most unexpected place (onside a top-level method, unexpectedly skipping the rest of it's body).

    The main disadvantage is the potential overhead (you can replace the Thread+join with just the yield if that's enough in your scenario).

提交回复
热议问题