Understanding Ruby Nested Functions

I am studying ruby ​​at the moment. I am trying to understand how closures work, and how they differ from functions. I fully understand that closing should be done through proc or lambda .

I am trying to get a deep understanding of ruby. Thus, I check all kinds of unorthodox code. I am trying to understand why line 3 works and line 5 is an error.

x=123
def b(x)
    p x
    def a(u)
      p x # why is this an error?!?!?
    end
    a 4
end

b 1
  • If a cannot access the parameters of b, why doesn't he access the global x = 123?
  • Why does this work if I explicitly use change lines 1 and 5 for global "$ x"?
  • Why does this work if I use lambda explicitly?

This is a purely educational exercise, I am doing this to understand what is happening under the hood.

+3
source share
2

- " ". , //, . / , .

, .

,

3

x = 123
def b(x)
    p x # this "x" is "x the parameter", not "x the local variable from outer scope"
        # that why it works. If you tried to access the local var, it wouldn't work.
    def a(u)
      p x # like here, see? Doesn't work.
    end
    a 4
end

b 1
+4

, , - , def "" ( Ruby?) - def - . - , "" . , def a, "" b; a, , , , b . a . .

, , def .

+3

All Articles