1

I would like to create an iterator that I can pass to a method for the method to call.

#!/usr/bin/env ruby

puts "------------------------------------"
puts "1 This works."
puts "------------------------------------"       
1.times {|who| puts "Position #{who} works!"}

puts "------------------------------------"
puts "2 This works."
puts "------------------------------------"       
aBlock = Proc.new { |who| puts "Position #{who} also works!" }       
2.times &aBlock

puts "------------------------------------"
puts "3 This works."
puts "------------------------------------"       
def eachIndex
  3.times { |i| yield i }
end

eachIndex &aBlock

puts "------------------------------------"
puts "4 This does not work."
puts "------------------------------------"       
iterator = lambda { |name| yield name }       
iterator.call(4) {|who| puts "Does not work #{who}:-("}

puts "------------------------------------"
puts "5 This does not work."
puts "------------------------------------"       
iterator = lambda { |name,&block| yield name }       
iterator.call(5) {|who| puts "Does not work #{who}:-("}

puts "------------------------------------"
puts "6 This does not work."
puts "------------------------------------"       
iterator = Proc.new { |name,&block| yield name }       
iterator.call(6) {|who| puts "Does not work #{who}:-(" }

Can lambda's or proc's be iterators in Ruby? I would like to pass them to a class as a parameter.

Mike Stitt
  • 25
  • 4

1 Answers1

1

Here is the way to do it

iterator = -> (name, &block) { block.call name }
iterator.call(4) { |who| puts "It works now #{who} :)" }

P.S. Note i use a shortcut here for a lambda, -> called stabby lambda

Nikita Misharin
  • 1,961
  • 1
  • 11
  • 20
  • Awesome! Thanks, that's exactly what I was looking for. – Mike Stitt Aug 08 '17 at 16:34
  • Maybe not so fast. The lambda function does call the block, which is a step in the right direction, but it should yield multiple times like an iterator. – Mike Stitt Aug 08 '17 at 16:40
  • But perhaps it ends up being a different type of iterator one that repeatedly calls the block rather than repeatedly yielding to the block. – Mike Stitt Aug 08 '17 at 16:44
  • 1
    Nikita, I placed my tweak to your answer here: [https://stackoverflow.com/questions/4982630/trouble-yielding-inside-a-block-lambda/45574588#45574588] – Mike Stitt Aug 08 '17 at 17:47
  • @MikeStitt Interesting tweak. Thanks. You could refactor it a little, to something like [this](https://gist.github.com/TheSmartnik/f673af8452b924daf1e24e0c9115cb74) – Nikita Misharin Aug 09 '17 at 09:10