对这个ruby片段的行为感到困惑
很抱歉问这个问题,但我真的需要完成这件事。我希望能够传入一个字符串并去掉stop_单词。我有以下资料:对这个ruby片段的行为感到困惑,ruby,Ruby,很抱歉问这个问题,但我真的需要完成这件事。我希望能够传入一个字符串并去掉stop_单词。我有以下资料: 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
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
我做错了什么
提前thx为什么要将结果作为数组我不知道,但是
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
def self.check\u零件术语
术语_部分=术语拆分(“”)
tmp_part=[]创建一个数组
术语|parts.每个do|part|
t=self.normalize部分#normalize返回一个空数组
#或仅一个元素(术语)中的一个。
tmp_part如果您只想过滤掉术语并获得一个大小写单词数组,那么它很简单
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"]
我刚刚复制了您的代码并运行了它(ruby 1.9.3),它返回了[[“here”]、[“is”]、[“my”]、[“char”]
,正如预期的那样。我在ruby 1.9.2p290(2011-07-09版本32553)[i686 linux]
,ruby 1.8.7(2012-02-08补丁级别358)[i686 linux]
,ruby 1.9.3p194(2012-04-20版本35410)上得到了预期的结果[i686 linux]
旁注:这似乎是一个新手代码,它几乎不惯用,两种方法都可以简化很多。
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"]