Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `return` in ruby `each` method

Tags:

return

ruby

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?

like image 820
Iggy Avatar asked Apr 09 '26 10:04

Iggy


1 Answers

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.

like image 135
sawa Avatar answered Apr 11 '26 19:04

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!