-
Notifications
You must be signed in to change notification settings - Fork 85
/
closures.rb
49 lines (39 loc) · 871 Bytes
/
closures.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Lambda's also enforce a closure and so are able to keep their context across
# objects, as demonstrated below:
require 'json'
class Bar
attr_reader :l
def initialize(h = {})
@l = h[:l] || ->(_) { p "no-op"; false }
end
def dothing
result = l.call("Mark")
p "result = #{ result }"
end
end
class Foo
def initialize
@h = {
l: ->(name) { p "hello #{ name }"; foo_test }
}
@bar = Bar.new(@h) # remove @h to test for defensive behaviour
end
def start
@bar.dothing
end
private
def foo_test
p "I'm internal to Foo class"
raise ::JSON::ParserError
true # never reached due to above line triggering an error
rescue ::JSON::ParserError
p "caught an error"
false
end
end
foo = Foo.new
foo.start
# => "hello Mark"
# => "I'm internal to Foo class"
# => "caught an error"
# => "result = false"