Method-scope-lab
Objectives
Define a method that takes in an argument and pass a variable in as that argument.
Understand that a variable defined inside a method cannot be used outside of that method.
Instructions
Part I: Passing a Variable Into a Method
Open up lib/catch_phrase.rb. You should see the following method:
def catch_phrase
puts phrase
endNote that the method is trying to puts out a variable called phrase.
Let's take a look at the test for this method in spec/catch_phrase_spec.rb:
describe "#catch_phrase" do
it "puts out a catch phrase" do
phrase = "It's-a me, Mario!"
expect{catch_phrase}.to output("It's-a me, Mario!\n").to_stdout
end
endGo ahead and run the test for this method only by typing rspec spec/catch_phrase_spec.rb into your terminal in the directory of this lab. You should see the following error:
This error is occurring because the code inside the #catch_phrase method is trying to use the phrase variable but it's not present inside the scope of the #catch_phrase method. It is out of scope. Let's fix it!
We need to pass phrase into our #catch_phrase as an argument. Let's do it:
Re-define the
#catch_phrasemethod to take in an argument of a phrase.Change the test in
spec/catch_phrase_spec.rbto match the following:
Part II: Understanding Method Scope
Open up lib/rescue_princess_peach.rb and take a look at the following method:
Notice that the body of this method is setting a variable, status equal to a value of "rescued". Do you think we will be able to access this variable outside of the method? Let's find out!
1 . Un-comment the following lines in your lib/rescue_princess_peach.rb file:
2 . Run the file with ruby lib/rescue_princess_peach.rb in your terminal. You should see the following:
We are getting a NameError because status is undefined. Wait a minute, you might be wondering. Didn't we define status inside the #rescue_princess_peach method? We did, but variables defined inside a method are not available outside of that method. They are only available within the scope of that method.
Go back and comment out lines 11 and 12 of rescue_princess_peach.rb.
Run the test suite and you'll see that we are passing all of our tests. If you open up the spec/rescue_princess_peach_spec.rb file, you'll see the following test:
Notice the last expectation of our test: expect{puts status}.to raise_error(NameError). We expect any attempt to use the status variable to be met with a NameError. Our program, outside of the #rescue_princess_peachmethod, just doesn't know what it is.
View Method Scope Lab on Learn.co and start learning to code for free.
Last updated