我想创建一个迭代器,我可以将其传递给方法来调用。
#!/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}:-(" }
lambda或proc是Ruby中的迭代器吗?我想将它们作为参数传递给一个类。
答案 0 :(得分:1)
以下是这样做的方法
iterator = -> (name, &block) { block.call name }
iterator.call(4) { |who| puts "It works now #{who} :)" }
P.S。注意我在这里使用lambda
的快捷方式,->
称为stabby lambda