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?

1

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.