Skip to content

Instantly share code, notes, and snippets.

@juderosen
Last active January 2, 2016 15:59
Show Gist options
  • Save juderosen/8326847 to your computer and use it in GitHub Desktop.
Save juderosen/8326847 to your computer and use it in GitHub Desktop.
Various infinite loops in Ruby
# 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.
##
@juderosen
Copy link
Author

How could I forget until? Oh well, it's fixed now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment