In Ruby, how can I check if some file contains some word? I've tried this:
在Ruby中,我如何检查某个文件是否包含某个单词?我已经试过这个:
foo = File.open('some-file', 'r').read
foo.index(/^word$/)
But this won't work.
但这是行不通的。
2 个解决方案
#1
7
File.readlines('some-file').grep(/word/)
Remeber that ^
matches against the beginning of a line, and $
matches against the end of a line. So if you search for ^xyz$
you are really searching for either xyz\n
(beginning of file) or \nxyz\n
(somewhere in the middle of the file). No other strings will match.
记得^匹配一行的开始,美元与一行的结束。如果你搜索xyz $ ^你真正寻找xyz \ n(开始文件)或\ nxyz \ n(中间的文件)。没有其他字符串匹配。
#2
2
You are searching for a line, which contains just that word. Maybe a less constrained search helps:
你正在搜索一行,它只包含这个词。也许一个不那么受约束的搜索会有所帮助:
foo.index(/word/)
#1
7
File.readlines('some-file').grep(/word/)
Remeber that ^
matches against the beginning of a line, and $
matches against the end of a line. So if you search for ^xyz$
you are really searching for either xyz\n
(beginning of file) or \nxyz\n
(somewhere in the middle of the file). No other strings will match.
记得^匹配一行的开始,美元与一行的结束。如果你搜索xyz $ ^你真正寻找xyz \ n(开始文件)或\ nxyz \ n(中间的文件)。没有其他字符串匹配。
#2
2
You are searching for a line, which contains just that word. Maybe a less constrained search helps:
你正在搜索一行,它只包含这个词。也许一个不那么受约束的搜索会有所帮助:
foo.index(/word/)