# 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
7
A
답변
11
물론 거부 할 수있다 :
odd, even = list.partition &:odd?
1
odd = []
even = []
list = [1..20]
list.each {|x| x.odd? ? odd << x : even << x }
0
pguardiario 말했듯이의 partition
방법은 가장 직접적인 방법입니다 . 또한 Set#divide
을 사용할 수
require 'set'
list = (1..10).to_a
odd, even = Set.new(list).divide(&:odd?).to_a.map{|x| x.to_a}
0
당신은 아래에 시도 할 수 :
odd,even = (0..20).group_by(&:odd?).values
p odd,even
출력 : 방법 내장
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
좋은, 그러나 당신이 당신의 자신의 방법을 추가로 반대 이 작업을 수행 할'Array'? – MrDanA
그래, 난 원숭이 패치에 대해 생각하고 있었다 Array 그것을 추가하려면 - 루비가 이미 내장 된 것 같지만, 워드 프로세서에서 아무것도 볼 수 없었어 – house9