method scope?

Explain why the following code raises an exception.

str = "hello"

def a_method
puts str

This code will raise an exception NameError: undefined local variable or method str for main:Object, because this would be a method call to a_method. Inside this method it asks for ruby to puts str, str variable is initialized outside this method. But on a method call you cannot pass in local variables unless you pass them in as parameters to the method. Methods have their own scope.

So I would pass in the variable to this method like so.

str = 'hello'

def a_method(str)
puts str




Explain why the last line outputs “hello”. What’s the underling principle in this code example?

str = "hello"

def a_method
str = "world"

puts str

The last line outputs “hello” because it was initialized outside the scope of this method, and since the method isn’t passing in the variable str it cannot assess that variable. SO when we do puts str it sees that it was initialized as “hello”, it cannot see what happened inside the method since it cannot access the variable in the method since it wasnt brought in as a parameter.

this is an example of method scope and variable scope. Methods have their own scope. Since the variable str wasn’t brought in as a parameter to the method, inside the method variable str is initialized in its own scope(not accessible outside this method).

Once outside this method, we have no access to the variable str that was initialized inside the method. Instead we have access to the local variable str that was initialized outside our method, in the current scope and the value of str = “hello” .




Leave a Reply

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

You are commenting using your 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: