0

我有一个循环/遍历某些东西的函数,我希望它接收对设置停止条件/做某事的函数的引用。例如,在一个类中:

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);

我看过,但没有找到这样的东西。谢谢

4

2 回答 2

4

Normally it is done with blocks.

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

Then

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
于 2013-03-08T18:06:17.510 回答
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)
于 2013-03-08T18:14:36.357 回答