Last active
January 27, 2018 20:55
-
-
Save bensherman/aeb708e886146db3c1aea8fef8e96c1a to your computer and use it in GitHub Desktop.
ruby loops
This file contains 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
# looping in ruby, from "The Ruby Way" by Hal Fulton | |
# added some rubymine stuff to get it cleanly inspected. | |
list = %w(alpha bravo charlie delta echo) | |
# 1 - while | |
i = 0 | |
while i < list.size do | |
print "#{list[i]} " | |
i += 1 | |
end | |
puts | |
# 2 - until | |
i = 0 | |
until i == list.size do | |
print "#{list[i]} " | |
i += 1 | |
end | |
puts | |
# 3 - post-test while / do while | |
i = 0 | |
begin | |
print "#{list[i]} " | |
i += 1 | |
end while i < list.size | |
puts | |
# 4 - post-test until / do until | |
i = 0 | |
begin | |
print "#{list[i]} " | |
i += 1 | |
end until i == list.size | |
puts | |
# 5 - for | |
# this one is bad form - rubymine complains! | |
# noinspection RubyForLoopInspection | |
for x in list do | |
print "#{x} " | |
end | |
puts | |
# 6 - each iterator | |
list.each do |x| | |
print "#{x} " | |
end | |
puts | |
# 7 - loop method | |
i = 0 | |
n = list.size - 1 | |
loop do | |
print "#{list[i]} " | |
i += 1 | |
break if i > n | |
end | |
puts | |
# 8 - loop method | |
i = 0 | |
n = list.size - 1 | |
loop do | |
print "#{list[i]} " | |
i += 1 | |
break unless i <= n | |
end | |
puts | |
# 9 - times iterator | |
n = list.size | |
n.times do |this_i| | |
print "#{list[this_i]} " | |
end | |
puts | |
# 10 - upto iterator | |
n = list.size - 1 | |
0.upto(n) do |this_i| | |
print "#{list[this_i]} " | |
end | |
puts | |
# 11 - for with an iterator | |
n = list.size - 1 | |
# rubymine complains that this is a dumb for loop. | |
# correct fix is to use a for.each, see 11.1 | |
# noinspection RubyForLoopInspection | |
for this_i in 0..n do | |
print "#{list[this_i]} " | |
end | |
puts | |
# 11.1 each - what rubymine want to change 11 into | |
(0..n).each {|this_i| | |
print "#{list[this_i]} " | |
} | |
puts | |
# 12 - each_index iterator | |
list.each_index do |x| | |
print "#{list[x]} " | |
end | |
puts | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment