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

局部变量
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

解决方法

您当然可以在相应的救援块中访问begin中定义的局部变量(当然,假设在设置变量之后引发了异常).

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

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

你可以做些什么来解决这个问题,就是在块之前定义变量(你可以将它设置为nil),然后在块内设置它.

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...