红宝石选择并在一种方法中拒绝 [英] Ruby Select and Reject in one method

查看:149
本文介绍了红宝石选择并在一种方法中拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有内置的方法,将合并的选择功能(找到所有该块等于真)和拒绝(找到所有该块相当于为false)?

Is there any built in method that would combine the functions of select (find all which the block equates to true) and reject (find all which the block equates to false)?

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

不会太辛苦做我自己,但美国国立卫生研究院和所有。 :)

Wouldn't be too hard to do it myself but NIH and all that. :)

推荐答案

看起来好像<一个href=\"http://www.ruby-doc.org/core/classes/Enumerable.html#M001496\"><$c$c>Enumerable.partition是你是什么了。

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...

这篇关于红宝石选择并在一种方法中拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆