微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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?

原文地址:https://www.jb51.cc/ruby/269007.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐