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.
entities
is 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.
你可以使用懒惰的枚举器 :
board = entities.lazy.map { |e| find_board(e) }.detect { |b| b }
尝试:
board = entities.find {|e| b = findBoard(e) and break b }
There is unfortunately no perfectly clean way of doing this in Ruby. I'd suggest the mildly ugly
board = nil
entities.find { |e| board = findBoard( e ) }
board
find
will work the same as each
except that it will short-circuit as soon as board is set to a non-nil value.
board = nil
entities.each { |e| board = findBoard(e) ; break unless board.nil?}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.