2

I have an array of strings that looks like this:

["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"]

I am trying to match the string "Greater New York City Area" to each element in this array and return another array containing the index of each match.

For the example above, the answer should be [0,3].

I can do this by manually iterating through each element, but that does not seem like the proper way to do it.

I need something like .find_all, but it needs to return the index not the value.

1
  • You need index or value? Commented May 21, 2012 at 3:26

2 Answers 2

5

try this:

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]
Sign up to request clarification or add additional context in comments.

Comments

2

Use the "each_with_index" method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.