Ruby元素匹配

时间:2016-05-26 13:41:17

标签: ruby

我试图找到字符串变量的第一个和第二个实例的索引。我希望能够使用任何预定义的字符串变量,但是当我尝试这样做时,它会给我一个错误。我希望能够声明多个字符串变量,如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]

2 个答案:

答案 0 :(得分:2)

据我了解,您只需要将变量传递给正则表达式。试试这个:

find_xx_instance = aa.each_with_index.select{|i,idx| i =~ /#{xx}/}

答案 1 :(得分:0)

我假设给你一个字符串数组arr,字符串str和整数n,并希望返回a的数组{ {1}}元素n,其中iistr的第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