我想要讀取文件並創建一個twitter句柄數組。該文件是趨勢鳴叫的隨機收集,片段是:在塊內使用.match()
@David_Cameron @britishchambers #BCCConf Mention of pay rises in the NHS. But what about all the redundancies to enable these pay rises?
在這種情況下,代碼應該返回
["@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
區塊內執行此操作,那就更好了。
請提供樣本輸入和輸出。 – daremkd 2015-02-10 19:54:22
@Emily你應該更新問題,而不是將東西填入評論。 – 2015-02-10 19:58:53
如果至少有一個有價值,您應該接受答案。但是,並不急於這樣做。選擇一個答案太快可能會阻礙其他答案,這是一個禮貌的做法,讓人們在選擇一個答案之前有時間完成答案。許多SO成員在選擇前至少等待幾個小時。當需要做出選擇時,選擇一個你認爲最有幫助的選項。 – 2015-02-10 21:43:30