我有一个循环/遍历某事的函数,我想让它接收一个设置stop creiteria /做某事的函数的引用。 例如,在一个类中:
def a(func_stop,i)
ret = nil # default
while(i < 0 )
if (func_stop(@lines[i]))
ret = i
break
end
end
return ret
end
我的想法是我可以传递对函数的引用,有点像PERL'S
func1(\&func, $i);
我看过了,但未能找到这样的东西。 感谢
答案 0 :(得分:4)
通常用块来完成。
def a(max, &func_stop)
puts "Processing #{max} elements"
max.times.each do |x|
if func_stop.call(x)
puts "Stopping"
break
else
puts "Current element: #{x}"
end
end
end
然后
a(10) do |x|
x > 5
end
# >> Processing 10 elements
# >> Current element: 0
# >> Current element: 1
# >> Current element: 2
# >> Current element: 3
# >> Current element: 4
# >> Current element: 5
# >> Stopping
答案 1 :(得分:0)
你也可以试试这个:
def a(func_stop,i)
ret = nil # default
while(i < 0 )
if (func_stop.call(@lines[i]))
ret = i
break
end
end
return ret
end
a(method(:your_function), i)