2010-10-29 61 views
8

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

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

第一个为我工作,我是否赋给变量内部或'开始... rescue'外块。 – 2010-10-29 18:11:44

+0

@Antal我在开始块内使用事务,并且我已经在事务内定义了对象。它会导致问题吗?我更新了我的问题。 – 2010-10-29 18:16:21

+0

你是指本地人吗? – xtofl 2010-10-29 18:16:53

回答

27

你肯定可以访问相应的rescue块(假设当然在begin定义的局部变量,异常已经提高,后变量被设置)。

你不能做的是访问块内定义的块外部的局部变量。这与例外无关。看到这个简单的例子:

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 
+0

我有更新我的问题。你能帮忙吗? – 2010-10-29 18:26:03

+0

@krunal:我更新了我的答案。 – sepp2k 2010-10-29 18:32:53

相关问题