2013-03-08 58 views
0

我有一个函数可以遍历/遍历一些东西,并且我希望它能够接收一个函数的引用来设置stop_ititeria/do something。 例如,在一类:将对Ruby中方法的引用传递给另一个方法

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的

func1(\&func, $i); 

我已经看过,但没能找到这样的事情。 谢谢

+1

'i'不循环内改变? – tokland 2013-03-08 18:30:20

+0

@lines来自哪里? – sunny1304 2013-03-08 18:44:41

回答

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 
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) 
相关问题