如何重构两个循环以在Ruby

时间:2017-05-23 16:53:14

标签: ruby

我有以下代码,并希望循环只存在一次,但我的返回语句各有不同:

def valid?
  patterns.each do |pattern|
    match_data = text.match(pattern)
    if match_data
      return true
    end
  end
  false
end

def pattern_matched
  patterns.each do |pattern|
    match_data = text.match(pattern)
    if match_data
      return pattern.source
    end
  end
  nil
end

我不想在州内存储任何东西,因为我希望这些功能是纯粹的,彼此独立。

如何编写一个运行循环的辅助函数但返回true / false OR pattern / nil?

1 个答案:

答案 0 :(得分:5)

怎么样:

def valid?
  !pattern_matched.nil?
end

def pattern_matched
  patterns.detect { |pattern| text.match(pattern) }&.source
end

我还替换了each循环,因为找到第一个匹配元素detect似乎是一个更好的选择。