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

倾然丶 夕夏残阳落幕 提交于 2019-12-13 02:29:12

问题


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.


回答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



来源:https://stackoverflow.com/questions/45571644/in-ruby-can-you-use-the-lambda-or-or-proc-call-method-to-invoke-an-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!