ruby-on-rails – 用于在1次操作中选择和拒绝2个数组的ruby数组(可枚举)方法

# this code works
list = (0..20).to_a
# => [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] 

odd = list.select { |x| x.odd? }
# => [1,19] 

list.reject! { |x| x.odd? }
# => [0,20] 

# but can i emulate this type of functionality with an enumerable method?
set = [1,10]
# => [1,10] 
one,five,ten = set
# => [1,10] 
one
# => 1 
five
# => 5 
ten
# => 10

# ------------------------------------------------
# method I am looking for ?
list = (0..20).to_a
odd,even = list.select_with_reject { |x| x.odd? }
# put the matching items into the first variable
# and the non-matching into the second

解决方法

当然,你可以这样做:
odd,even = list.partition &:odd?

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...