Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby return different type in "array.each"

Please consider this code:

    board = entities.each { |e| return if not findBoard( e ).nil? }

It should do exactly the same as:

    for e in entities
        board = findBoard( e )

        if not board.nil?
            break
        end
    end

but the first one does not work while the second one goes fine.

entitiesis an array of Entity objects and findBoard() returns a Board object or nil.

Entity and Board are not related classes.

I know that the second code works fine but since I am starting to learn Ruby, I am wondering if it is any more elegant way to do this so I ask, is it possible for an each method to return a different object type other than the objects in array (I guess it should)?

Really thanks.

like image 270
j4x Avatar asked Jun 24 '26 00:06

j4x


1 Answers

You could use a lazy enumerator:

board = entities.lazy.map { |e| find_board(e) }.detect { |b| b }
like image 119
Stefan Avatar answered Jun 26 '26 21:06

Stefan



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!