2

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

["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” 与该数组中的每个元素进行匹配,并返回另一个包含每个匹配项索引的数组。

对于上面的示例,答案应该是 [0,3]。

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

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

4

2 回答 2

5

试试这个:

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]
于 2012-05-21T03:29:00.357 回答
2

使用“each_with_index”方法。

于 2012-05-21T03:28:42.303 回答