9

我想使用部分字符串搜索数组,然后获取找到该字符串的索引。例如:

a = ["This is line 1", "We have line 2 here", "and finally line 3", "potato"]
a.index("potato") # this returns 3
a.index("We have") # this returns nil

usinga.grep将返回完整的字符串, usinga.any?将返回正确的真/假语句,但都不返回找到匹配项的索引,或者至少我不知道该怎么做。

我正在编写一段代码,该代码读取文件,查找特定标头,然后返回该标头的索引,以便可以将其用作将来搜索的偏移量。如果不从特定索引开始搜索,我的其他搜索将得到误报。

4

1 回答 1

22

使用块。

a.index{|s| s.include?("We have")}

或者

a.index{|s| s =~ /We have/}
于 2013-01-16T00:13:15.820 回答