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.

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

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.