On Mon, May 18, 2020 at 4:16 PM Craig Russell <apache....@gmail.com> wrote:
>
> Here's the code I'm debugging:
>
>     def self.find(name)
>       files = self.listnames
>       if files
>         stem = Regexp.new Regexp.quote name.downcase.gsub(' ','-')
>         Wunderbar.warn "EmeritusFiles.find #{files}"
>         Wunderbar.warn "EmeritusFiles.find stem: #{stem}"
>         files.each do |file|
>           Wunderbar.warn "EmeritusFiles.find #{stem} in #{file}"
>           break file if stem =~ file
>         end
>       end
>     end
>
> What I want is to return the string (actual file name) which represents a 
> match to the pattern formed by the name with blanks replaced by \- because - 
> is a special character in regex.
>
> What actually happens is that the each loop doesn't break out but instead 
> returns all of the files. I don't know exactly what is returned but it shows 
> up as a series of file names separated by commas.
>
> Anyone see the obvious bug here?

Without an explicit return statement, Ruby will return the value of
the last statement, which is the if statement.

If files is nil/false, the value is nil.

Otherwise, what will be returned is the value of the last statement,
which is the call to each.

Each will call the block, possibly multiple times, and this execution
may or may not break, but that won't affect what each will return.

each will return the original array:

https://ruby-doc.org/core-2.4.1/Array.html#method-i-each

You might consider using the find method instead of calling each:

https://ruby-doc.org/core-2.7.1/Enumerable.html#method-i-find

> Thanks,
> Craig
>
> Craig L Russell
> c...@apache.org

- Sam Ruby

Reply via email to