gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:57:31 24 4
gpt4 key购买 nike

# 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, 3, 5, 7, 9, 11, 13, 15, 17, 19]

list.reject! { |x| x.odd? }
# => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

# but can i emulate this type of functionality with an enumerable method?
set = [1,5,10]
# => [1, 5, 10]
one, five, ten = set
# => [1, 5, 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?

关于ruby-on-rails - 在 1 个操作中选择和拒绝 2 个数组的 ruby​​ 数组(可枚举)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15845311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com