"Just Another Victim of the Ambient Morality" <ihatespam / hotmail.com> wrote 
in message news:0pg0j.14858$zb2.9793 / fe02.news.easynews.com...
>
> "Alvaro Perez" <alvaro.pmartinez / gmail.com> wrote in message 
> news:8b39ce45165efee679037915d6b29bb0 / ruby-forum.com...
>> Hi there,
>>
>> something that I think should not be very difficult, but i'm struggling
>> with:
>>
>>  def find(name, where)
>>      for father in where
>>         if (father.name==name) then
>>             found = thing
>>             break
>>         else
>>             find(name, father.children)
>>         end
>>      end
>>      found
>>  end
>>
>> I have an array with parent objects, some of them have children. I want
>> to find an object with the same name and return in, otherwise nil.
>>
>> The problem is that, once I start searching inside the children of some
>> father, and I found what I'm looking for, I break the loop inside (array
>> father.children). But then the search continues in the level above. I
>> would like to break the complete search. How can it be done?
>
>    I don't understand, exactly, what you're doing but there are some 
> things that are obviously wrong with your code and some techniques you 
> should probably know to implement what you're doing.
>    First of all, have you tested your own code?  Your find() method 
> doesn't even store the value of its recursive call.  It might still work 
> if that recursive call is the last thing your method does but you 
> explicitly evaluate the variable "found," ensuring that the recursed value 
> is never returned since it can never be the last thing done.
>    Secondly, using literal for loops is very pythonic and, thus, un-ruby 
> like.  Wouldn't you rather where.each through elements?
>    Finally, there are many different ways to solve your problem.  If where 
> is enumerable, you can use the find method:
>
> def weird_find(name, container)
>    container.find do |father|
>        if father.name == name
>            father  # Is this what you're looking for?
>        else
>            weird_find(name, father.children)
>        end
>    end
> end

    Actually, I was hitting the crack pipe pretty hard when I wrote this bit 
with find().  It doesn't do what I thought it did.
    You'll just need to use each with break...

def weird_find(name, container)
    container.each do |father|
        if father.name == name
            found = father  # Is this still what you're looking for?
            break
        else
            found = weird_find(name, container)
            break if found
        end
    end
    found
end

    ...this is untested but should work...