OILS / demo / survey-closure.rb View on Github | oils.pub

49 lines, 34 significant
1
2def create_context(x)
3 y = 20
4 binding
5end
6
7binding = create_context(10)
8puts binding
9puts binding.class
10
11vars = binding.eval("local_variables")
12puts vars
13puts vars.class
14
15# Why doesn't this work?
16#myproc = proc { puts "x: #{x}, y: #{y}" }
17
18# You need this longer thing
19myproc = proc { puts "x: #{binding.eval("x")}, y: #{binding.eval("y")}" }
20
21# Execute the block in the context
22binding.instance_exec(&myproc)
23
24
25#
26# 2025-03 - var vs. setvar
27#
28
29puts ""
30
31def 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}"
46end
47
48outer_function
49