Using `return` in ruby `each` method -


i trying create code search , returns array location when type search name. following code works ('ned' correctly displays value of 1):

array1 = ['lucky', 'ned', "dusty'"] counter = 0  name = 'ned' array1.each |lookup|   if lookup == name     puts counter   end   counter += 1 end 

however, when use return counter in place of puts counter, code returns error. here error code:

unexpected return (repl):7:in `block in initialize' (repl):5:in `each' (repl):5:in `initialize' 

i don't understand why says initialize. not understand why works puts , not work return. explain why cannot return value while prints it?

because return way escape from method (definition). don't have method definition anywhere. can use break purpose.


Comments