3

I am trying to create a code that does search and returns its array location when I type the search name. The following code works ('Ned' correctly displays value of 1):

array1 = ['Lucky', 'Ned', "Dusty'"]
counter = 0

name = 'Ned'
array1.each do |lookup|
  if lookup == name
    puts counter
  end
  counter += 1
end

However, when I use return counter in the place of puts counter, the code returns error. Here is the error code:

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

I don't understand why it says initialize. I do not understand why it works with puts and does not work with return. Will someone explain why it cannot return the value while it successfully prints it?

sawa
  • 165,429
  • 45
  • 277
  • 381
Iggy
  • 5,129
  • 12
  • 53
  • 87
  • 1
    Possible duplicate of [Unexpected Return (LocalJumpError)](http://stackoverflow.com/questions/17800629/unexpected-return-localjumperror) – Makoto Jan 25 '16 at 03:05

1 Answers1

7

Because return is a way to escape from a method (definition). You don't have a method definition anywhere. You can use break for that purpose.

sawa
  • 165,429
  • 45
  • 277
  • 381