I would like to explain the scope of variables with fairly simple code.
It is assumed that the following controller is described.
class SampleController < ApplicationController
def test1
sample_1 = 10
test3(sample_1)
end
def test2
sample_2 = 10
test4
end
private
def test3(num)
sample_3 = num + 10
end
def test4
sample_4 = sample_2 + 10
end
end
Apparently, the test1 action will call the test3 (num) action of the private method, and the test2 action will call the test4 action of the private method.
If you write from the conclusion first, the call and processing of test3 (num) from test1 works well, but you can call test4 from test2, but the processing does not work and an error occurs.
In test1, we define sample_1 = 10
internally and pass it as an actual argument to test3 (num) in the notation test3 (sample_1)
.
def test1
sample_1 = 10
test3(sample_1)
end
Inside test3, the passed sample_1 is assigned to the formal argument num. In other words, if you write it in an easy-to-understand manner (?), It means num = 10
.
def test3(num)
sample_3 = num + 10
end
Since the number was successfully passed to num in this way, the calculation of the contents of test3 (num) is actually sample_3 = 10 + 10
Then, sample_3 = 20
.
In test2, test4 is called after defining sample_2 = 10
internally.
def test2
sample_2 = 10
test4
end
Inside test4, sample_2 = 10
defined in test2 can be used, so the calculation of the contents is practical.
Since sample_4 = 10 + 10
, it is not sample_4 = 20
.
why?
def test4
sample_4 = sample_2 + 10
end
This is because sample_2 cannot be used inside test4.
No matter how much you define sample_2 = 10
inside test2, it has nothing to do with test4.
This is what is called the scope of variables. If you write from the conclusion first, the variables that can be used inside test4
That is. (To be precise, I think I could have used a global variable, but I'll omit it because it makes the story confusing.)
Hmm? Instance variable? That's the one with @.
So if you want to use sample_2 = 10
in test4
def test2
@sample_2 = 10
test4
end
Define it like that, even in test4
def test4
sample_4 = @sample_2 + 10
end
You can use it by adding @ to it, and it will be sample_4 = 20
.
Recommended Posts