Ruby on Rails Scope question

print "Enter a number: "
n = gets.to_i
begin
result = 100 / n
rescue
puts “Your number didn’t work. Was it zero???”
exit
end
puts “100/#{n} is #{result}.”

In the above example, how come the result is being used outside the
begin - end block? How does it
still remain in scope? TIA.

Am 07.10.2006 um 09:55 schrieb Bala P.:

print "Enter a number: "
n = gets.to_i

result = 0

begin
result = 100 / n
rescue
puts “Your number didn’t work. Was it zero???”
exit
end
puts “100/#{n} is #{result}.”

Regards
Florian

On Oct 7, 2006, at 12:55 AM, Bala P. wrote:

In the above example, how come the result is being used outside the
begin - end block? How does it
still remain in scope? TIA.

begin…end blocks do not create a new scope but use the existing one.
They are mainly a construct to deliminate a block of code that can
throw an error and need to be rescued or retried.

-Ezra

No, you don’t need to declare the result variable before you begin to
use it. It just springs up
into existence inside the block.