-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-iterators.rb
90 lines (59 loc) · 1.76 KB
/
2-iterators.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
# We continue our whirlwind tour of programming with iterators.
# Iterators and loops do stuff 0 or more times, depending on conditions.
# Here we set some variables:
number = 0
finish = 10
# And we tell Ruby to print 'number' as long as it is below 10:
while number < finish do
puts number
number = number + 1
end
# Easy eh?
# You can also rewrite it as:
until number == 10 do
puts number
number = number + 1
end
# Loops like the ones above can be dangerous.
# If you don't provide an exit condition that will ever be met...
# ...your computer will catch on fire and a kitten will die.
# while number != "feh" do
# puts number
# number = number + 1
# end
# Now on to conditionals! A programmers staple.
# Conditionals execute stuff _depending_ on whether a condition is met.
# For instance:
my_name = "Wojtek"
your_name = "Wojtek"
if my_name == your_name
puts "Wow 2 Wojteks!"
end
# If we change your name to something else...
# It won't execute:
your_name = "Sigismund Jones"
if my_name == your_name
puts "It's the same person!"
end
# You can also add an 'else' statement. It's pretty self explanatory.
if my_name == your_name
puts "Same person!"
else
puts "Not the same"
end
# There are tons of things you can check with an if statement. You can compare size:
windspeed = 100
if windspeed > 99
puts "Hurricane!"
elsif windspeed < 10
puts "Just a zephyr..."
end
# Notice the elsif addition. That just adds another condition to check against.
# Now on to my favorite iterator.
# It's called 'each', and it will serve you well.
# First, I'm going to create an array. That's like a list of things:
fellows = [ 'Arzu', 'Evgeny', 'Hanna', 'Ana', 'Olga', 'Natalia' ]
fellows.each do |person|
puts "Hello #{person}!"
end
# I love the 'each' iterator.