Ruby:获取数组和字符串之间每个匹配的索引

时间:2012-05-21 03:20:40

标签: ruby

我有一个字符串数组,如下所示:

["Greater New York City Area", "Saudi Arabia", "Bahrain", "Greater New York City Area", "Toronto Canada Area", "Nigeria", "Toronto Canada Area", "United Arab Emirates", "Toronto Canada Area", "Egypt", "Egypt", "Bangladesh", "Gurgaon India", "United Arab Emirates", "New Delhi Area India", "Saudi Arabia", "United Arab Emirates", "United Arab Emirates", "Toronto Canada Area", "Pakistan", "New Delhi Area India", "New Delhi Area India", "United Arab Emirates", "Mumbai Area India", "New Delhi Area India"]

我正在尝试将字符串“Greater New York City Area”与此数组中的每个元素匹配,并返回包含每个匹配项的 index 的另一个数组。

对于上面的例子,答案应为[0,3]。

我可以通过手动迭代每个元素来做到这一点,但这似乎不是正确的方法。

我需要像.find_all这样的东西,但它需要返回索引而不是值。

2 个答案:

答案 0 :(得分:4)

试试这个:

a = ["Greater New York City Area", "Saudi Arabia", "Bahrain", "Greater New York City Area", "Toronto Canada Area", "Nigeria", "Toronto Canada Area", "United Arab Emirates", "Toronto Canada Area", "Egypt", "Egypt", "Bangladesh", "Gurgaon India", "United Arab Emirates", "New Delhi Area India", "Saudi Arabia", "United Arab Emirates", "United Arab Emirates", "Toronto Canada Area", "Pakistan", "New Delhi Area India", "New Delhi Area India", "United Arab Emirates", "Mumbai Area India", "New Delhi Area India"]

results_with_index = a.each_with_index.select { |i, idx| i =~ /Greater New York City Area/} # [["Greater New York City Area", 0], ["Greater New York City Area", 3]] 

results_with_index.map! { |i| i[1] } # [0,3]

答案 1 :(得分:1)

使用“each_with_index”方法。