-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloops.rb
More file actions
49 lines (42 loc) · 1.09 KB
/
loops.rb
File metadata and controls
49 lines (42 loc) · 1.09 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
# while loop runs until a condition is false
num = 10
while num > 0 do
puts "value of num is now: #{num}"
num -= 1
end
# until is similar to the while loop, runs until the condition is false
i = 0
until i >= 10 do
puts "value of i: #{i}"
i += 1
end
# range
(1..5) # values from 1 upto 5, double dots include the upper value
(1...5) # values from 1 upto 4, tripple dots exclude the upper value
# the for loop is used to loop through a collection of items
my_letters_array = ['a', 'b', 'c', 'd']
for i in 0...my_letters_array.length
puts "#{my_letters_array[i]}"
end
# .times loop, this runs a loop a given number of times
i = 0
5.times do
puts "this is printed #{i + 1} times"
i += 1
end
3.times do |number|
puts "Print time: #{number + 1}"
end
=begin
1. upto loop is used to loop up to a specific value
2. downto loop is used to loop down to a specific value
=end
# this loop prints values from 0 upto 5 -- ie lowers to highest
0.upto(5) do |num|
puts num
end
print "----------------------------\n"
# this loop prints values from 5 to 0 ie highest to lowest
5.downto(0) do |num|
puts num
end