我试图找到字符串变量的第一个和第二个实例的索引。我希望能够使用任何预定义的字符串变量,但是当我尝试这样做时,它会给我一个错误。我希望能够声明多个字符串变量,如ss,aa,ff等,并使用它们代替xx。有人可以帮助我吗?
#aa is a predefined array
xx = "--help--"
find_xx_instance = aa.each_with_index.select{|i,idx| i =~ /xx/}
#/--help--/works but not /xx/
find_xx_instance.map! {|i| i[1]}
#gives me info between the first two instances of string
puts aa[find_xx_instance[0]+1..find_xx_instance[1]-1]
答案 0 :(得分:2)
据我了解,您只需要将变量传递给正则表达式。试试这个:
find_xx_instance = aa.each_with_index.select{|i,idx| i =~ /#{xx}/}
答案 1 :(得分:0)
我假设给你一个字符串数组arr
,字符串str
和整数n
,并希望返回a
的数组{ {1}}元素n
,其中i
是i
中str
的第i + 1个实例的索引。
例如:
arr
这是一种方式:
arr = %w| Now is the time for the Zorgs to attack the Borgs |
#=> ["Now", "is", "the", "time", "for", "the", "Zorgs", "to", "attack", "the", "Borgs"]
str = "the"
nbr = 2
可以写
b = arr.each_index.select { |i| arr[i]==str }
#=> [2, 5, 9]
b.first(nbr)
#=> [2, 5]
对于像这样的小问题,这很好,但如果arr.each_index.select { |i| arr[i]==str }.first(nbr)
很大,最好在找到arr
nbr
个实例后终止计算。我们可以通过创建Lazy enumerator:
str
以下是第二个示例,清楚地说明arr.each_index.lazy.select { |i| arr[i]==str }.first(nbr)
#=> [2, 5]
在找到lazy
中的nbr
字符串str
后停止计算:
arr