加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:27:53 所属栏目:百科 来源:网络整理
导读:# this code workslist = (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 enumerab
# 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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读