在块内部使用.match()

  • 本文关键字:match 内部 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块内执行此操作,那将是更可取的。

我做错了什么?

通过将[]放在/@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提取所有出现的内容。

最新更新