Skip to content

Instantly share code, notes, and snippets.

@MilanGrubnic70
Last active August 29, 2015 14:00
Show Gist options
  • Save MilanGrubnic70/11092549 to your computer and use it in GitHub Desktop.
Save MilanGrubnic70/11092549 to your computer and use it in GitHub Desktop.
Iterators: loop, for, each, & times.
# An iterator is a Ruby method that repeatedly invokes a block of code.
# The 'break' keyword: Your Get Out of Jail Free card: it breaks a loop as soon as its condition is met.
# The 'Loop' method: The simplest iterator is the loop method.
loop { print "Hello, world!" } # WARNING! Infinite loop!
i = 0
loop do
i += 1
print "#{i}"
break if i > 5 #Break!
end
# "The 'Next' keyword: Used to skip over certain steps in the loop.
for i in 1..5
next if i % 2 == 0
print i
end
#=> 1 3 5
# The 'Each' method: Applies an expression to each element of an object, one at a time.
object.each do |item|
#Do something
end
# The 'Times' method: A super compact for loop: it can perform a task on each item in an object a specified number of times.
10.times { puts "Milan" }
#=> Milan Milan ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment