-3

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
sulu fiti
  • 1
  • 3
  • Hi and welcome to Stack Overflow. So - you've got an answer, but to help you write better question sin future, i should say that it's unclear what you're mystified about. It would probably help us if you explained what you do know, and what you don't know - just dumping a line of code and saying "i'm mystified" leads me to think "so am I" ;) My questions would be "what are you mystified about? why do you need to know this? what have you tried when you played with it in 'irb'? – Taryn East May 20 '15 at 03:56
  • do you understand similar kinds of methods (eg find/select/reject) too, or is there something specific about detect that is a problem? is it just *this specific usage* of detect that you don't understand, or have you seen simpler versions that do make sense? etc etc any way that you can narrow down from "I'm mystified" to an actual question will help us to help you in future :) – Taryn East May 20 '15 at 03:57
  • 1
    Hi Taryn, thanks for taking the time out to help with my question and also for the advice on how to pose questions on S.O. in the future. Sorry, I should have elaborated further in my initial question - I was not sure how '6' was returned from the code that I supplied. I understand it perfectly now thanks to the answer from @squiguy. Thank you so much people. Much appreciated. – sulu fiti May 20 '15 at 04:18
  • detect will return first occurrence of result match – Ritesh Karwa May 20 '15 at 04:56
  • Also thanks to all who those down voted my very first question on SO. Way to make a guy feel welcome. – sulu fiti Jun 20 '15 at 02:56

1 Answers1

2

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.

squiguy
  • 32,370
  • 6
  • 56
  • 63