开发者

Ruby Select and Reject in one method

Is there any built in method that would combine the functions of Enumerable.select (find all which the block equates to true) and Enumerable.reject (find all w开发者_运维技巧hich the block equates to false)?

Something like

good, bad = list.magic_method { |obj| obj.good? }


Looks as if Enumerable.partition is exactly what you are after.

= Enumerable.partition

(from ruby core)
------------------------------------------------------------------------------
  enum.partition {| obj | block }  -> [ true_array, false_array ]
  enum.partition                   -> an_enumerator

------------------------------------------------------------------------------

Returns two arrays, the first containing the elements of enum for
which the block evaluates to true, the second containing the rest.

If no block is given, an enumerator is returned instead.

   (1..6).partition {|i| (i&1).zero?}   #=> [[2, 4, 6], [1, 3, 5]]

Interesting, I didn't know that was there. ri is an amazing tool...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜