如何干掉这个红宝石代码

时间:2016-10-08 04:46:58

标签: ruby dry

我想干掉这段代码。我似乎无法弄清楚如何。

def get_all_verb_nodes
    all_verb_nodes = @all_nodes_ins_del_nodes.select { |node|
    previous_node = node.xpath('preceding-sibling::w:r').last
    base_word = previous_node.text.split.last.strip.delete('.!?,:') if previous_node
  words = get_node_text(node)
  next_node = node.next_element
  next_node_is_insert_or_delete = is_insert_or_delete?(next_node.name) if next_node
  next_node_word = next_node.text.strip if next_node
  words.length <= 2 && words.any? { |word| is_a_verb?(base_word+word) || is_a_verb?(word) && !is_pluralized?(base_word+word, base_word+next_node_word) } && !next_node_is_insert_or_delete
    }
end


def get_all_article_nodes
    all_article_nodes = @all_nodes_ins_del_nodes.select { |node|
    previous_node = node.xpath('preceding-sibling::w:r').last
    base_word = previous_node.text.split.last.strip.delete('.!?,:') if previous_node
  words = get_node_text(node) 
  next_node = node.next_element
  next_node_is_insert_or_delete = is_insert_or_delete?(next_node.name) if next_node
  next_node_word = next_node.text.strip if next_node
  words.length <= 2 && words.any? { |word| @articleset.include?(word) || (@articleset.include?(base_word) if word == 'n') } && !@articleset.include?(next_node_word) && !next_node_is_insert_or_delete
    }
end

除了定义函数特定要求的最后一行之外,两者几乎完全相同。

任何想法都赞赏。

1 个答案:

答案 0 :(得分:2)

这是第一次切入。我移动了东西,所以他们按逻辑分组,以促进产量。

def get_all_nodes
  @all_nodes_ins_del_nodes.select do |node|
    previous_node = node.xpath('preceding-sibling::w:r').last
    base_word = previous_node.text.split.last.strip.delete('.!?,:') if previous_node

    next_node = node.next_element
    next_node_is_insert_or_delete = is_insert_or_delete?(next_node.name) if next_node
    next_node_word = next_node.text.strip if next_node

    words = get_node_text(node) 
    words.length <= 2 &&
    !next_node_is_insert_or_delete &&
    yield(words, base_word, next_node_word)
  end
end

all_verb_nodes = get_all_nodes do |words, base_word, next_node_word|
  words.any? do |word|
    is_a_verb?(base_word + word) ||
    is_a_verb?(word) &&
    !is_pluralized?(base_word + word, base_word + next_node_word)
  end
end

all_article_nodes = get_all_nodes do |words, base_word, next_node_word|
  !@articleset.include?(next_node_word) &&
  words.any? do |word|
    @articleset.include?(word) || (@articleset.include?(base_word) if word == 'n')
  end
end