Ruby 新绑定更改和循环逻辑抽象

Ruby 新绑定更改和循环逻辑抽象,ruby,Ruby,我有两个不同方法的循环,看起来非常相似。我想在Proc.new 这很有效 def matches_base? proc_exec = Proc.new do |subclass, breakpoint| # next and return are meant to act inside the loop and quit it if needed response = process_match(subclass) next if response == :conti

我有两个不同方法的循环,看起来非常相似。我想在
Proc.new

这很有效

def matches_base?
  proc_exec = Proc.new do |subclass, breakpoint|
    # next and return are meant to act inside the loop and quit it if needed
    response = process_match(subclass)
    next if response == :continue
    return true if response == false

    return response
  end

  subclasses(BASE_NAMESPACE).each do |subclass|
    proc_exec.call(subclass)
  end
  false
end
这里明显的问题是
proc\u exec
是在方法本身内部定义的,但我想在另一个方法中使用它

def matches_breakpoints?
  breakpoints.fetch.each do |breakpoint|
    # I want to include the proc_exec here too
  end
  false
end
所以我试着在课堂上提取它,就像这样

这不起作用

def proc_exec
  Proc.new do |subclass, breakpoint|
    response = process_match(subclass)
    next if response == :continue
    return true if response == false

    return response
  end
end

def matches_base?
  subclasses(BASE_NAMESPACE).each do |subclass|
    proc_exec.call(subclass)
  end
  false
end
然后我可以在这两个实例方法中像调用
proc\u exec.call那样调用它。目前它抛出

 LocalJumpError:
   unexpected return
我尝试了很多技巧,比如
instance\u eval
instance\u exec
,但都没有成功。我现在没办法了


下面是我想要的易于执行的简化示例。

class MyLoops
  def proc_exec
    Proc.new do |num|
      next if num == 1
      # we want this `return` to act in the method context
      # as it would do if I defined it inside a method directly
      return if num == 4
      puts "Current number : #{num}"
    end
  end

  def method_a
    [0,1,2].each do |num|
      proc_exec.call(num)
    end
    false
  end

  def method_b
    [3,4,5].each do |num|
      proc_exec.call(num)
    end
  end
  # this `false` below should never be reached ; that's the trick
  false
end

loops = MyLoops.new
loops.method_a
loops.method_b

你不能既有蛋糕又吃。如果您想从proc中
return
中止该方法,则它必须位于该方法的词法作用域*(也就是说“它必须在同一方法中定义”)

另一种方法是让proc/lambda返回一个“stop”值,调用者将使用该值中止其执行

(遗憾的是,您对instance_eval/instance_exec的实验方向错误。这些方法只会更改当前的
self
。这个问题与当前的
self
无关,而是与当前的词法范围有关,在该范围内执行
返回



*您遇到的错误是由于
return
试图从不再运行的方法(
proc\u exec
)返回而导致的。

经验法则:不要在ruby save中使用
return
来提前返回。您可以编写一个吗?@mudasobwa:有人可能会认为每次返回都是提前返回。:)@SergioTulentsev“early return”是一个习语,与中的“fail fast”类似:)@mudasobwa最终的循环返回是在方法到达结尾之前退出
false
这都是事先考虑的,这里的一切都有原因是的,这本质上重复了mudasobwa的(现已删除)回答,但代码更少。不幸的是,这里似乎没有什么魔术可以奏效。这就是我害怕的,这就是为什么我问的原因,现在我得到了确认…停止逃跑(魔术)似乎是最干净的解决方案。。。