0

So I believe that I understand this code. I was prompted in codewars to return the duplicate in the provided array. This is what I came up with after some searching. I am very new to Ruby and would like to thoroughly understand this piece of code rather than just using it to pass the code challenge.

Correct me if I am wrong, or add anything I am missing...

  • arr is the array.
  • .detect is a method that passes each entry in the enum through a block. it then returns the first for which the block is not false.
  • in this case, it passes it through:

    {|e| arr.rindex(e) != arr.index(e)}  
    
  • the process of this block is that e represents each entry in the enum.

  • .rindex(e) searches from the last to first e in the array and returns the matching array object described in the argument () portion of the code.
  • .index(e) returns the first object in the array that is true.

So, to wrap this all up, ".rindex" checks starting from the end of the array for the first true object, while .index does the same but from the start of the array until they hit the number that makes .rindex and .index false. Since the block itself is true (arr.rindex(e) is not equal to arr.index(e)), detect returns the object that is a duplicate.

    arr.detect {|e| arr.rindex(e) != arr.index(e) }

This all still feels very high level to me and it would be beneficial for someone to break this down a bit better for me. Thanks in advance!

Erik Aasland
  • 167
  • 1
  • 11

2 Answers2

2

You're very close, but #index and #rindex return the array index (position) at which an element matching e is found, starting from the left and the right respectively. You know you've found a duplicate when the value returned from index and rindex do not match. For example, given:

arr = [:a, :b, :b, :c]
arr.index(:b) # => 1
arr.rindex(:b) # => 2

The array indices for each entry are 0, 1, 2, 3. Here, searching from the left, :b is first found at position 2 (index 1), but searching from the right, is first found at position 3 (index 2). Since the indexes don't match, you know that you've found two elements with the same value, but different positions in the array, and thus you have a duplicate.

(As an amusing aside, this technique is one of my better-voted SO answers. Heh.)

Community
  • 1
  • 1
Chris Heald
  • 61,439
  • 10
  • 123
  • 137
1

Shortly:

  • index(e) is the index of the first slot of the array containing e
  • rindex(e) is the index of the last slot of the array containing e

If index(e) is different from rindex(e) then there are at least two slots containing e.

Mario Zannone
  • 2,843
  • 12
  • 18