代码之家  ›  专栏  ›  技术社区  ›  krunal shah

为什么我们不能访问救援内部的局部变量?

  •  9
  • krunal shah  · 技术社区  · 14 年前

    局部变量

    begin
      transaction  #Code inside transaction 
        object = Class.new attributes
        raise unless object.save!
      end 
    rescue
      puts object.error.full_messages # Why can't we use local varible inside rescue ?
    end
    

    实例变量

    begin
      transaction  #Code inside transaction 
        @object = Class.new attributes
        raise unless @object.save!
      end 
    rescue
      puts @object.error.full_messages # This is working fine.
    end
    
    1 回复  |  直到 14 年前
        1
  •  28
  •   sepp2k    14 年前

    begin rescue

    define transaction() yield end
    transaction do
      x = 42
    end
    puts x # This will cause an error because `x` is not defined here.
    

    x = nil
    transaction do
      x = 42
    end
    puts x # Will print 42
    

    begin
      object = nil
      transaction do  #Code inside transaction 
        object = Class.new attributes
        raise unless object.save!
      end 
    rescue
      puts object.error.full_messages # Why can't we use local varible inside rescue ?
    end