Ruby: Going Enumerated

I would like to concede in an enumerated block in order to create some kind of template test code.

Basically, I would like to do something like this (simplified):

def iterator( enumerable, &block )
  iterations = enumerable.size
  counter = 0
  enumerable.each do |item|
    counter +=1
    puts "Iterating #{counter}/#{iterations}..."
    yield
  end
end

Then, I would like to use this method to wrap this template test code around a block that I would repeat so that I could call something like:

# assuming foo is an enumerable collection of objects
iterator foo do
  item.slow_method
  item.mundane_method
  item.save
end

... and when this code is executed, I get the following log output:

Iterating 1/1234...
Iterating 2/1234...
Iterating 3/1234...

It seems that such a thing should be possible, but I could not figure out the syntax, as well as what it is called (to see it).

, OUTSIDE, , , INSIDE . , , .

, , . , , , .

+5
1

Ruby yield .

yield item

"" "" .

, .

, :

class Item
  def initialize(id)
    @id = id
  end
  def slow_method()
    puts "slow #@id"
  end
  def mundane_method()
    puts "mundane #@id"
  end
  def save()
    puts "save #@id"
  end
end

foo = [Item.new(100), Item.new(200), Item.new(300)]

def iterator(enumerable, &block)
  iterations = enumerable.size
  counter = 0
  enumerable.each do |item|
    counter +=1
    puts "Iterating #{counter}/#{iterations}..."
    yield item
  end
end

iterator foo do |item|
  item.slow_method
  item.mundane_method
  item.save
end
+7
source

All Articles