Loops & Iterators

I ‘While’ & ‘Until’ Loops

i. The ‘While’ Loop 1/18

Save and Submit

ii. Danger: Infinite Loops! 2/18

i = 0
while i < 5
 puts i
 i = i + 1
end

iii. The ‘Until’ Loop 3/18

counter = 1
until counter > 10
 puts counter
 counter += 1
end

iv. More Assignment Operators 4/18

counter = 1
while counter < 11
 puts counter
 counter += 1
end

II ‘For’ Loops

i. ‘The ‘For’ Loop 5/18

Save and Submit

ii Inclusive and Exclusive Ranges 6/18

for num in 1..15
 puts num
end

iii. Building Your Own 7/18

for num in 1..20
 puts num
end

III  Iterators & Blocks

i. The Loop Method 8/18

i = 20
loop do
 i -= 1
 print "#{i}"
 break if i <= 0
end

ii. Next! 9/18

i = 20
loop do
 i -= 1
 next if i % 2 > 0
 print "#{i}"
 break if i <= 0
end

iii. Saving Multiple Values 10/18

my_array  = [1,2,3,4,5]

iv. The .each Iterator 11/18

array = [1,2,3,4,5]

array.each do |x|
 x += 10
 print "#{x}"
end

v Try It Out! 12/18

odds = [1,3,5,7,9]

odds.each do |x|
 x = x * 2
 print x
end

vi. The .times Iterator 13/18

5.times { print "Hot summer day!"}

IV Review

i. Looping with ‘While’ 14/18

i = 1
while i <= 50 do
 print i
 i += 1
end

ii. Looping with ‘Until’ 15/18

i = 1
until i > 50 do
 print i
 i += 1
end

iii. Looping with ‘For’ 16/18

i = 1
for i in 1..50
 print i
end

iv. Loop the Loop with Loop 17/18

i = 0
loop do
 i += 1
 print "Ruby!"
 break if i == 30
end

v. Iterating with .times 18/18

30.times { print "Ruby!"}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s