I have trouble understanding the detect
method in Enumerable
. I tried with the sample code:
(1..6).detect { |i| i % 2 == 0 and i % 3 == 0 }
#=> 6
But I'm still mystified. Any help would be much appreciated.
According to the documentation this method returns the first element in the enumerable object that the block returns true.
Therefore, the first number in that range that is both divisible by 2 and 3 is 6 and thus it is returned. If this were not the case and no number was divisible by both 2 and 3, then the method will return nil
.
It's a way to "detect" the first object that makes the block true.