-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path04-loops.rb
More file actions
78 lines (63 loc) · 1.39 KB
/
04-loops.rb
File metadata and controls
78 lines (63 loc) · 1.39 KB
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
# loops and iterators
# loop
loop do
print "Continue (y/n)? > "
choice = $stdin.gets.chomp
break if choice == 'n'
end
# for-loop
for x in 1..10
puts x
end
# while-loop
x = 1
while x <= 10
puts x
x += 1
end
# until loop
x = 1
until x == 11
puts x
x += 1
end
# an iterator is a method that accepts a block
# times iterator
3.times do |x|
puts "Hurray for Ruby!"
end
# upto iterator
3.upto(5) do |x|
puts "Hurray again for Ruby! #{x}"
end
# step iterator
1.upto(10) do |x|
puts "#{x} is a odd number"
end
# each iterator
consoles = [ "wii u", "ps4", "xboxone"]
consoles.each do |x|
puts "Should I get a #{x}?"
end
# select iterator
# the opposite of the select iterator is called reject
words = [ "ramen", "pizza", "coffee", "coke", "fruit" ]
short_words = words.select { |word| word.length >= 5 }
puts short_words.inspect
# collect iterator
words = [ "today", "i", "learned" ]
# create an array with reversed words
reversed_words = words.collect { |word| word.reverse }
puts reversed_words.to_s
# each_slice iterator
# the slice will be an array
(1..10).each_slice(3) do |slice|
puts slice.to_s
end
# use map() to reverse all words in an array
words = [ "happy", "spring", "break"]
words.map { |word| word.reverse }
# use inject() to calculate average score
scores = [ 88, 89, 100, 79, 93 ]
total = scores.inject { |total,score| total += score }
average = total/scores.length