范围 variables/guards

Scope variables/guards

是否可以有一个保证在范围退出时完成的变量。

具体来说,我想要一个守卫:在初始化时调用特定函数,并在作用域退出时调用另一个特定函数的东西。

最好明确地完成:

class Guard
  def initialize
    # Init things here
  end

  def close
    # clean up things here
  end
end

def my_method
  guard = Guard.new
  # do things here
ensure
  guard.close
end

然后一个常见的模式是使用 yielding 方法提供更好的接口。在使用外部资源时,您会注意到在标准库中经常看到这一点:

class Guard
  def self.obtain
    guard = new
    yield guard
  ensure
    guard.close
  end

  # ...
end

Guard.obtain do |guard|
  # do things
end

当然,如果消费者不应该与之交互,则生成实际资源对象是可选的。