-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenumerable.rb
77 lines (54 loc) · 1.17 KB
/
enumerable.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
def sum_odd_indexed(array)
sum = 0
array.each_with_index { |num, index| sum += num if index.odd? }
sum
end
def even_numbers(array)
array.select { |num| num.even? }
end
def short_words(array, max_length)
array.reject { |word| word.size > max_length }
end
def first_under(array, limit)
array.find { |num| num < limit }
end
def add_bang(array)
array.map { |word| word + "!" }
end
def concatenate(array)
array.reduce("") { |a, e| a + e }
end
def sorted_pairs(array)
result = []
array.each_slice(2) do |slice|
result << slice.sort
end
result
end
# hash exercise
letters = {"c" => 3, "e" => 1, "l" => 1, "n" => 1, "t" => 1, "x" => 8, "y" => 4}
score = 0
"excellently".each_char {|letter| score += letters[letter] }
point_totals = Hash.new(0)
"excellently".each_char {|letter| point_totals[letter] += letters[letter] }
point_totals.values.reduce(0, :+)
# custom iterators
# yield usage
def n_times n
1.upto(n) do |count|
yield count
end
end
n_times(8) do |n|
puts "#{n} situps"
puts "#{n} pushups"
puts "#{n} chinups"
end
# it should print something like this
# 1 situps
# 1 pushups
# 1 chinups
# ...
# 5 situps
# 5 pushups
# 5 chinups