-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclosures&lambdas.rb
87 lines (55 loc) · 887 Bytes
/
closures&lambdas.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def countBy(number, step)
return Proc.new do
number += step
end
end
counter1 = countBy(2, 3)
puts counter1.call
puts counter1.call
puts counter1.call
puts counter1.call
puts
def doWithNum(number, lam)
puts "Arity is #{lam.arity}"
lam.call(number)
end
myLambda = lambda do |n|
n *= n
end
puts doWithNum(5, ->(x) {
x*x
})
puts
def n_times(thing)
return lambda { |n| thing * n }
end
p1 = n_times(5)
puts p1.call(2.5)
p2 = n_times('Na')
puts p2.call(15)+' BATMAAAN'
puts
def my_if(condition, then_clause, else_clause)
if (condition)
then_clause.call
else
else_clause.call
end
end
5.times do |val|
my_if(val < 2, -> {
puts "#{val} is small"
}, -> {
puts "#{val} is big"
})
end
puts
def my_while(condition, &body)
while condition.call
body.call
end
end
a = 0
my_while(-> { a < 3 }) do
puts a
a += 1
end