Created
August 28, 2012 21:02
-
-
Save malachaifrazier/3504326 to your computer and use it in GitHub Desktop.
Loops & Iterators in Ruby Examples (Tested with Ruby 1.9.3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
## Count to 50 | |
1.upto(50) {|n| puts n} | |
## Count Down to 1 | |
50.downto(1) {|n| puts n} | |
## Count to 20 | |
(1..20).each {|n| puts n} | |
## OR | |
(1..20).each do |n| | |
puts n | |
end | |
## Counts to 46 | |
i = 0 | |
until i === 46 | |
i += 1 | |
puts "We have #{i} of these." | |
end | |
## Counts to 10 | |
for i in 0..10 | |
puts "Count #{i}! Sound Off!" | |
end | |
## While Loops | |
i=1 | |
while i < 11 | |
print "#{i} " | |
i+=1 | |
end | |
## Loop Break (Single Line) | |
i=0 | |
loop do | |
i+=1 | |
print "#{i} " | |
break if i==10 | |
end | |
## Next Keyword and skip 3 | |
i=0 | |
loop do | |
i+=1 | |
next if i==3 | |
print "#{i} " | |
break if i==10 | |
end | |
## Infinite Redo Keyword (does not evaluate the terminating condition) | |
i=1 | |
until i > 10 | |
print "#{i} " | |
i+=1 | |
redo if i > 10 | |
end | |
################################################################## | |
## Array Counter to 10 | |
for value in [1,2,3,4,5,6,7,8,9,10] | |
print "#{value} " | |
end | |
## Iterator | |
[1,2,3,4,5,6,7,8,9,10].each do |value| | |
print "#{value} " | |
end | |
##Times Iterator (ZERO INDEX!) | |
101.times do |i| | |
print "#{i}\n" | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment