是否有一种内置方法可以结合Enumerable.select
(查找所有块等于 true 的元素)和Enumerable.reject
(查找所有块等于 false 的元素)的功能?
类似于:
good, bad = list.magic_method { |obj| obj.good? }
看起来像是Enumerable.partition
正是你所需要的。
= 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]]
很有趣,我不知道那里有这个东西。 ri
是一个很棒的工具...
MethodFinder.find([*1..4], [[1,3],[2,4]], &:odd?) #=> [:partition]
。 - Michael Kohl