如何使用部分字符串搜索数组,并返回索引?

时间:2013-01-16 00:09:19

标签: ruby arrays string indexing

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

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

使用a.grep将返回完整的字符串,使用a.any?将返回正确的true / false语句,但是都不会返回找到匹配项的索引,或者至少我无法计算如何做到这一点。

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

1 个答案:

答案 0 :(得分:17)

使用块。

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

a.index{|s| s =~ /We have/}
相关问题