加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 找到第一个没有引发错误的proc,并获得它的返回值

发布时间:2020-12-17 02:30:50 所属栏目:百科 来源:网络整理
导读:场景是这样的:根据输入本身的某些质量,您有一些输入要使用几种可能的过程中的一种进行处理.在尝试向每个输入发送输入之前,您不知道提前工作. 假设您有一系列可能的过程尝试.你想要的是找到第一个不引发错误的proc,并获得它的返回值,最好是一次通过.如果没有
场景是这样的:根据输入本身的某些质量,您有一些输入要使用几种可能的过程中的一种进行处理.在尝试向每个输入发送输入之前,您不知道提前工作.

假设您有一系列可能的过程尝试.你想要的是找到第一个不引发错误的proc,并获得它的返回值,最好是一次通过.如果没有找到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

解决方法

这是我的解决方案,注意救援修改器拯救了StandardError,我认为没有任何方法可以在不进行多行阻止的情况下改变它.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读