I have an array in Ruby that has some duplicate elements. E.g.:
fruits = ["apples", "bananas", "apples", "grapes", "apples"]
When I do the following:
fruits.index("apples")
# returns 0
I only get the first occurrence of "apples"
which is, in this case, fruits[0]
. Is there a way that I can run something similar to the above code and get the indexes of the other occurrences of "apples"
? If I can't run something similar to the above code, how else can I get the indexes of the duplicate elements?
Ruby Array objects have another method, count. In this case, you are interested in duplicates (objects which appear more than once in the array). The appropriate test is a.count (obj) > 1.
Use the uniq method to remove duplicate elements from arrays with minimal code. Remove duplicates. In an array, any element value may occur. But often we want just unique, non-duplicate elements. We invoke the uniq method to correct this problem. Array Uniq and "uniq!" remove all except the first element with a value.
If you are comparing two different arrays (instead of one against itself) a very fast way is to use the intersect operator & provided by Ruby's Array class. # Given a = ['a', 'b', 'c', 'd'] b = ['e', 'f', 'c', 'd'] # Then this... a & b # => ['c', 'd']
The array has two duplicated numbers: a 2 and a 3. We invoke the "uniq!" method, which operates in-place. So: When we call "uniq!" we do not assign another array to it. The methods imply changes the "values" array, which we reuse. Next: We create an array of strings. This one has three string values equalling "dog."
Taking a page from procedural languages, we could write:
fruits.each_index.select { |i| fruits[i]=="apples" }
#=> [0, 2, 4]
You can do this:
fruits.to_enum.with_index.select{|e, _| e == "apples"}.map(&:last)
# => [0, 2, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With