-
Notifications
You must be signed in to change notification settings - Fork 6
/
read.rb
58 lines (38 loc) · 901 Bytes
/
read.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
# Functions
def square(number)
number * number
end
square(10) # => 100
def repeater(string, repeat)
repeat.times do
puts string
end
end
repeater('Hi all', 10) # Hi all \n Hi all ...
# Blocks & Yield
def email(name='Adrian', &block)
puts "Hola #{name}"
yield
puts "Espero que estes muy bien, contestame pronto"
end
email 'Elias' do
puts "Nos vemos mañana temprano"
end
# Lambda & Reusing Code
greeter = -> { puts "Hello World" }
greeter.yield # Hello World
square = -> (number) { number * number}
square.yield(10) # 100
## Map
# Apply a function to a collection of elements
(1..5).map do |n|
n * n
end
# [1,4,9,16,25]
(1..5).map {|n| n * n } # [1,4,9,16,25]
(1..5).map(&:square) # [1,4,9,16,25]
(1..5).map(&square) # [1,4,9,16,25]
## Reduce
# Reduce a collection of elements to one value
(1..5).reduce {|acum, number| acum + number }
(1..5).reduce &:+