"Emmanuel Touzery" <emmanuel.touzery / wanadoo.fr> schrieb im Newsbeitrag
news:200305260838.02882.emmanuel.touzery / wanadoo.fr...
> Hello,
>
> it's a newbie question...
> i wanted to do something like:
>
> result1 = [1, 2, 3].find { |e|
> if e == 2
> return true
> else
> return false
> end
> }
> (with several if/else one in each other rather than one big condition,
for
> code readability)
>
> but I realised that 'return' does not apply to a block, but only to a
> function. it's a bit (actually very) un-intuitive for me, but anyway, is
> there a nicer solution than doing my current:
>
> item = [1, 2, 3].find { |e|
> result = false
> if e == 2
> result = true
> else
> result = false
> end
> result
> }
>
> for reference, here is my real code. I'm searching the current TV
program at
> showTime from a DB of tv programs i fetched from the net. a program for
sure
> has a start time (time), but not necessarily an end time (if it's the
last tv
> program on the web page, i can't know).
>
> # now find the current program for this
> # channel.
> programsForChannel.find { |program|
> result = false
> if program.time <= showTime
> if program.endTime
> # there is a endtime.
> # are we now before this end?
> if program.endTime > showTime
> result = true
> end
> else
> # program has no registered
> # end.
>   result = true
> end
> end
> result
> }
>
> any help appreciated!

In your case you can use "return" even with older versions of ruby if you
use a method:

def find
  [1, 2, 3].find { |e|
    return true if e == 2
  }

  false
end

Are you aware of the standard methods Enumerable#include?,
Enumerable#find, Enumerable#detect, Enumerable#select, Enumerable#find_all
and Enumerable#grep?  These should provide the functionality you need.

Regards

    robert