Ruby Select和Reject在一个方法中

Dre*_*rew 25 ruby arrays select filter

是否有任何内置方法可以组合Enumerable.select(查找块等于true的Enumerable.reject所有内容)和(找到块等于false的所有内容)的函数?

就像是

good, bad = list.magic_method { |obj| obj.good? }
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 36

看起来就像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]]
Run Code Online (Sandbox Code Playgroud)

有意思,我不知道那里有. ri是一个了不起的工具......

  • 刚刚也是针对这种方法的.我是Ruby on Rails的新手,在查看Enumerable的文档时,我想,"如果有一个我应该掌握的模块,那就是IT!" (4认同)