我编写了一个函数来查找Ruby字符串中子字符串的起始位置,从测试来看,它看起来是有效的:
def positions(substring, string)
string
.chars
.each_with_index
.select {|_, index| string[index ... index + substring.length] == substring}
.map(&:last)
end
p positions("foo", "The foo example: foo and bar and foo") #=> [4, 17, 33]
p positions("ab", "xxxabxxxabxx") #=> [3, 8]
我是不是问代码审查,我的问题是:Ruby中的哪个内置将完成相同的任务?
> "The foo example: foo and bar and foo".enum_for(:scan, "foo").map { $~.offset(0)[0] }
=> [4, 17, 33]
它是这样工作的:
enum_for(:scan, "foo")
使用scan("foo")作为它的map方法创建枚举器。当找到子字符串并且$~
是最后一个Regex匹配的全局变量并且Scan正在使用它时,Scan产生。offset(n)
是由第n个匹配
> "The foo example: foo and bar and foo".match(/foo/).offset(0)
=> [4, 7]
使用String#index
可能更清楚,因为它用于获取子字符串的索引:
def positions(substring, string)
arr = []; i = 0
while(i = string.index(substring, i))
arr << i; i += 1
end
arr
end