-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrocs-and-lambdas.rb
114 lines (80 loc) · 1.76 KB
/
rocs-and-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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
hello = lambda do
word = "Hello!"
puts word
end
p hello.class
hello.call
add_35 = lambda { puts 35 }
add_35.call
add_94 = -> { puts 94 }
add_94.call
hi_proc = proc do
hi = "Hi proc!"
puts hi
end
p hi_proc.class
hi_proc.call
smile = lambda do |left = '*', right = '*'|
puts "(#{left}.#{right})"
end
smile = lambda { |left = '*', right = '*'| puts "(#{left}.#{right})" }
smile.call
smile.call('-', '-')
smile.()
smile.('+', '+')
link_to = lambda { |href, text| puts "<a href='#{href}'>#{text}</a>" }
link_to.call 'blog.ru', 'My blog'
#link_to.call 'blog.ru'
#wrong number of arguments (given 1, expected 2) (ArgumentError)
#link_to.call 'blog.ru', 'My blog', ''
#wrong number of arguments (given 3, expected 2) (ArgumentError)
link_to = proc { |href, text| puts "<a href='#{href}'>#{text}</a>" }
link_to.call 'news.ru', 'My news'
link_to.call 'news.ru'
link_to.call 'news.ru', 'My news', ''
def start_game(money, options_type)
options = case options_type
when 1
lambda do |money|
return "Money is tight!" if money < 50
"=Welcome="
end
when 2
proc do |money|
return "Money is tight!" if money < 50
"=Welcome="
end
end
puts options.call(money)
end
start_game 50, 1
start_game 5, 1
start_game 50, 2
start_game 5, 2
# & - унарный амперсанд
def pizza_each(type, &block)
ingredients = case type
when "Margarita"
%w(tomato basil cheese)
when "Marinada"
%w(tomato garlic oregano)
end
ingredients.each &block
end
pizza_each("Margarita"){ |i| p i }
tell_about_pizza = lambda { |i| p i }
pizza_each "Marinada", &tell_about_pizza
class Cat
def initialize
@cat = case rand(3)
when 0 then "Cat 1"
when 1 then "Cat 2"
when 2 then "Cat 3"
end
end
def say_hello_cat
puts @cat
end
end
cat = Cat.new
cat.say_hello_cat