ruby scope examples

In the code below, explain why the last line outputs 2.
What’s the underlying principle this example illustrates?


str = 1

loop do
str = 2
break
end

puts str # output is 2`

the output of the last line is 2, because in ruby if a local variable is initialized outside a block with inner scope, the inner scope has access to that variable. The rule in ruby is that “Inner scope can access variables initialized in outer scope but not vice versa”

 

Explain why the code below raises an exception.


loop do
str = 2
break
end

puts str

This code raises an exception of undefined local variable or method for str because loop do..end is a method block invocation thus creating inner scope. The str = 2 was initialized inside this scope and not initialized outside the scope. SO if you try and access that local variable thats create in the scope of this block it will not have access to the variable. If you initialized this variable outside the block above the code you will be able to access the str variable on the outside.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: