Ruby中的一个方法实现Select和Reject

33

是否有一种内置方法可以结合Enumerable.select(查找所有块等于 true 的元素)和Enumerable.reject(查找所有块等于 false 的元素)的功能?

类似于:

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

2
我的methodfinder宝石可以帮助解决这样的问题:MethodFinder.find([*1..4], [[1,3],[2,4]], &:odd?) #=> [:partition] - Michael Kohl
OMFGBARBALE可以解决我很多问题。D: - Drew
1个回答

47

看起来像是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 是一个很棒的工具...


1
Ruby就是这样的。十有八九,如果你想到了一个有用的方法,它已经存在了。 :) - Andy
是的,这也是我发现的。 :) - Drew
4
刚刚也被引导到了这种方法。我是 Ruby on Rails 的新手,在查看 Enumerable 文档时,我想:“如果有一个模块我应该掌握,那就是它!”请注意,此翻译已经排除了解释和额外的内容。 - Tass

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接