Search code examples
rubylambdaiteratorproc

In Ruby, can you use the lambda or or Proc call method to invoke an iterator?


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.


Solution

  • 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