I started learning Ruby on Rails and found myself confounded by the syntax, so I had to read about somet of the Ruby syntax. I learned the syntax from http://www.cs.auckland
I think you could call it iterator, because often, the block function is called more than once. As in:
5.times do |i|
puts "#{i} "
end
"Behind the scenes", the following steps are made:
times of the object instance 5 is called, passing the code puts "#{i} " in a Proc object instance.times method, this code is called inside a loop, passing the current index as a parameter. That's what times could look like (it's in C, actually):class Fixnum
def times_2(&block) # Specifying &block as a parameter is optional
return self unless block_given?
i = 0
while(i < self) do
yield i # Here the proc instance "block" is called
i += 1
end
return self
end
end
Note that the scope (i.e. local variables etc.) is copied into the block function:
x = ' '
5.times do { |i| puts "#{i}" + x }