对这个红宝石片段的行为感到困惑

时间:2012-10-18 06:54:57

标签: ruby

很抱歉问这个,但我真的需要完成这件事。我希望能够传入一个字符串并删除stop_words。我有以下内容:

class Query
  def self.normalize term
    stop_words=["a","big","array"]
    term.downcase!
    legit=[]
    if !stop_words.include?(term)
      legit << term
    end
    return legit
  end

  def self.check_parts term
    term_parts=term.split(' ')
    tmp_part=[]
    term_parts.each do |part|
      t=self.normalize part
      tmp_part << t
    end  
    return tmp_part  
  end
end

我认为这只会返回不在stop_words列表中的术语,但我会找回一个空数组或传入的术语数组。就像这样:

ruby-1.9.2-p290 :146 > Query.check_parts "here Is my Char"
 => [[], [], [], ["char"]] 
ruby-1.9.2-p290 :147 >

我做错了什么?

事先提前

2 个答案:

答案 0 :(得分:0)

为什么你想把结果作为一个我不知道但不知道的数组

term_parts=term.split(' ')
term_parts.reject { |part| stop_words.include?(part) }

你可以写下你的期望。
顺便说一句,你有一个数组数组,因为

def self.check_parts term
    term_parts=term.split(' ')
    tmp_part=[]                 # creates an array
    term_parts.each do |part|
      t=self.normalize part     # normalize returns an empty array
                                # or one of only one element (a term).
      tmp_part << t             # you add an array into the array
    end  
    return tmp_part  
  end

答案 1 :(得分:0)

如果您只想过滤掉这些术语并获得一系列下层词汇,那很简单。

module Query
  StopWords = %w[a big array]
  def self.check_parts string; string.downcase.split(/\s+/) - StopWords end
end

Query.check_parts("here Is my Char") # => ["here", "is", "my", "char"]