Last active
January 2, 2016 15:59
-
-
Save juderosen/8326847 to your computer and use it in GitHub Desktop.
Various infinite loops in Ruby
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
# Loop | |
i = 0 | |
loop do | |
i+=1 | |
puts "To infinity and beyond! (#{i})" | |
end | |
# While | |
i = 0 | |
while true do | |
i+=1 | |
puts "To infinity and beyond! (#{i})" | |
end | |
# For | |
x = Float::INFINITY | |
i = 0 | |
for i in 0..x do | |
i+=1 | |
puts "To infinity and beyond! (#{i})" | |
end | |
# Each | |
x = Float::INFINITY | |
i = 0 | |
(1..x).each do | |
i+=1 | |
puts "To infinity and beyond! (#{i})" | |
end | |
# Until | |
i = 0 | |
until false == true do | |
i+=1 | |
puts "To infinity and beyond! (#{i})" | |
end | |
# Upto | |
x = Float::INFINITY | |
i = 0 | |
1.upto(x) do | |
i+=1 | |
puts "To infinity and beyond! (#{i})" | |
end | |
# Unfortunately, times doesn't work. | |
x = Float::INFINITY | |
i = 0 | |
x.times do | |
i+=1 | |
puts "To infinity and beyond! (#{i})" | |
end | |
#=> NoMethodError: undefined method `times' for Infinity:Float | |
## | |
# Of course, there are various ways of expressing these loops, but it's mostly personal preference/style. | |
# Hopefully, I haven't missed anything. | |
# For the purposes of infinite looping, loop is the simplest way to do it. | |
## |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How could I forget
until
? Oh well, it's fixed now.