Is there a method in Ruby that divides an array into two smaller arrays based on a logical condition?
假设我有一个数组中的元素列表,但是有一种合乎逻辑的方法可以将它们分成两组。我想根据该标准将这些元素放入两个较小的数组中。这是一些有效的代码,有助于说明我的意思:
1 2 3 4 5 6 | foo = ['a', 'bb', 'c', 'ddd', 'ee', 'f'] => ["a","bb","c","ddd","ee","f"] a = foo.select{|element| element.length == 1} => ["a","c","f"] b = foo.reject{|element| element.length == 1} => ["bb","ddd","ee"] |
我似乎记得看到过某种方式,单个方法调用可以同时分配 a 和 b,但我不记得它是什么。它看起来像
1 | matching, non_matching = foo.mystery_method{|element| element.length == 1} |
我是不是疯了,或者在 Ruby 和/或 Rails 中是否存在这样的方法?
是的! http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-partition
1 | matching, non_matching = foo.partition {|element| element.length == 1} |