场景是这样的:你有一些输入你想使用几种可能的过程之一来处理,这取决于输入本身的质量。在您尝试将输入发送给每个人之前,您不会提前知道哪个会起作用。
假设您有一系列可能的过程要尝试。您想要的是找到第一个不引发错误的过程,并获得它的返回值,最好一次通过。如果未找到 proc,则引发错误。
在 ruby 中你如何最好地做到这一点?
到目前为止,我的答案看起来像下面两个答案之一,但我正在寻找一种更惯用的方式。还有一种将 nil 的返回值视为有效的方法——现在这两种方法都将 nil 视为错误状态。
(1)
ret = nil
array_of_procs.find do |p|
begin
ret = p[input]
rescue
next
end
end
raise ArgumentError unless ret
(2)
ret = array_of_procs.inject(nil) do |memo, p|
memo = p[input] rescue next
break memo
end
raise ArgumentError unless ret
最佳答案
这是我的解决方案,请注意 rescue 修饰符拯救了 StandardError,我认为没有任何方法可以在不进入多行 block 的情况下更改它。
def first_valid_result(procs, input)
procs.each { |p| return p[input] rescue nil }
raise ArgumentError
end
这是规范
describe '#first_valid_result' do
let(:error_proc) { lambda { |input| raise } }
let(:procs) { [error_proc] * 2 }
let(:input) { :some_input }
it "returns the input from the first proc that doesnt raise an error" do
procs.insert 1, lambda { |input| input }
first_valid_result(procs, input).should == input
end
it "treats nil as a valid return value" do
procs.insert 1, lambda { |input| nil }
first_valid_result(procs, input).should be_nil
end
it "raises an ArgumentError when no valid proc exists" do
expect { first_valid_result procs, input }.to raise_error ArgumentError
end
end
关于ruby - 查找第一个未引发错误的过程,并获取其返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8775186/