In the case of iterators, think of them as an interface in Java: you can do a for-loop in Ruby, but all the objects that you might want to iterate over (should) implement the "everyone" method, which takes a block (i.e. closure, anonymous function).
Blocks are used universally in Ruby. Imagine you have this array:
[1, 2, 3, 4, 5, 6].each do |i| puts i.to_s end
Here you create an array, and then you call the "each" method on it. You give him a block. You can separate it like this:
arr = [1, 2, 3, 4, 5, 6] string_printer = lambda do |i| puts i.to_s end arr.each(&string_printer)
This kind of interface is implemented in other things: the Hash collection allows you to iterate over key-value pairs:
{:name => "Tom", :gender => :male}.each do |key, value| puts key end
Do..end can be replaced with curly braces, for example:
[1, 2, 3, 4, 5, 6].each {|i| puts i.to_s }
This iteration is made possible by the functional programming that Ruby uses: if you create a class that needs to iterate over something, you can also implement each method. Consider:
class AddressBook attr_accessor :addresses def each(&block) @addresses.each {|i| yield i } end end
All kinds of classes implement interesting functionality using this block template: for example, look at the String method each_line and each_byte.