Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we access local variable inside rescue?

Tags:

ruby

Local Variable

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

Instance Variable

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
like image 873
krunal shah Avatar asked Oct 29 '10 18:10

krunal shah


1 Answers

You most certainly can access local variables defined in a begin, in the corresponding rescue block (assuming of course, the exception has been raised, after the variable was set).

What you can't do is access local variables that are defined inside a block, outside of the block. This has nothing to do with exceptions. See this simple example:

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

What you can do to fix this, is to define the variable before the block (you can just set it to nil) and then set it inside the block.

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

So if you change your code like this, it will work:

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
like image 182
sepp2k Avatar answered Sep 28 '22 05:09

sepp2k