我想读取一个文件并创建一个twitter句柄数组。该文件是一个趋势推文的随机集合,其片段为:
@David_Cameron@britishchambers#BCCConf提到NHS。但是,为实现这些加薪而进行的所有裁员又如何呢?
在这种情况下,代码应该返回
["@David_Cameron", "@britishchambers"]
放置/@w+/.match(word)[0]
在irb中有效,但一旦我将其放入具有each
或map
的块中:
def read_file(file_path)
text = File.open(file_path, 'r'){ |f| f.read}.split(" ")
text.each{|word| /@w+/.match(word)[0] }
end
然后我收到错误:
NoMethodError: undefined method `[]' for nil:NilClass
我做错了什么?此外,如果我可以在file.open
块内执行此操作,那将是更可取的。
我做错了什么?
通过将[]
放在/@w+/.match(word)
之后,您假设word
始终与/@w+/
匹配,从而返回一个MatchData
对象,但这不是真的。例如,#BCCConf
与/@w+/
不匹配,在这种情况下,/@w+/.match(word)
是nil
。[]
未在nil
上定义。
def read_file(file_path)
text = File.read(file_path)
text.scan(/@w+/).flatten
end
读取文件,然后使用#scan
提取所有出现的内容。