我想读取一个文件并创建一个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
块内执行此操作,那将更为可取。
答案 0 :(得分:1)
我做错了什么?
在[]
之后放置/@\w+/.match(word)
,您假设word
始终与/@\w+/
匹配,从而返回MatchData
个对象,这不是真的。例如#BCCConf
与/@\w+/
不匹配,在这种情况下/@\w+/.match(word)
为nil
。 []
上未定义nil
。
答案 1 :(得分:0)
def read_file(file_path)
text = File.read(file_path)
text.scan(/@\w+/).flatten
end
阅读文件,然后使用#scan
提取所有出现的内容。