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!