| 1 |
|
| 2 | def create_context(x)
|
| 3 | y = 20
|
| 4 | binding
|
| 5 | end
|
| 6 |
|
| 7 | binding = create_context(10)
|
| 8 | puts binding
|
| 9 | puts binding.class
|
| 10 |
|
| 11 | vars = binding.eval("local_variables")
|
| 12 | puts vars
|
| 13 | puts vars.class
|
| 14 |
|
| 15 | # Why doesn't this work?
|
| 16 | #myproc = proc { puts "x: #{x}, y: #{y}" }
|
| 17 |
|
| 18 | # You need this longer thing
|
| 19 | myproc = proc { puts "x: #{binding.eval("x")}, y: #{binding.eval("y")}" }
|
| 20 |
|
| 21 | # Execute the block in the context
|
| 22 | binding.instance_exec(&myproc)
|
| 23 |
|
| 24 |
|
| 25 | #
|
| 26 | # 2025-03 - var vs. setvar
|
| 27 | #
|
| 28 |
|
| 29 | puts ""
|
| 30 |
|
| 31 | def outer_function
|
| 32 | counter = 10 # Outer function defines its own `counter`
|
| 33 | puts "Counter in outer_function is: #{counter}"
|
| 34 |
|
| 35 | # Inner function also defines its own `counter`
|
| 36 | inner_function = lambda do
|
| 37 | counter = 5 # Inner function defines its own `counter`
|
| 38 | puts "Mutating counter in inner_function: #{counter}"
|
| 39 | end
|
| 40 |
|
| 41 | # Calling the inner function
|
| 42 | inner_function.call
|
| 43 |
|
| 44 | # Back to outer function, `counter` remains unchanged
|
| 45 | puts "Counter in outer_function after inner call: #{counter}"
|
| 46 | end
|
| 47 |
|
| 48 | outer_function
|
| 49 |
|