在块内使用.match()

时间:2015-02-10 19:50:55

标签: ruby regex

我想读取一个文件并创建一个twitter句柄数组。该文件是趋势推文的随机集合,代码片段为:

  

@David_Cameron @britishchambers #BCCConf提到加薪   NHS。但是,为了实现这些加薪,所有裁员呢?

在这种情况下代码应该返回

["@David_Cameron", "@britishchambers"]

/@\w+/.match(word)[0]置于irb中,但只要我将其放入包含eachmap的块中:

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块内执行此操作,那将更为可取。

2 个答案:

答案 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提取所有出现的内容。