2009-12-18 2 views
7

로 선택배열은 내가 할 수있는 여러 조건 루비

@items = @items.select {|i| i.color == 'blue'} 
@items = @items.select {|i| i.color == 'blue' || i.color == 'red'} 

내가 색상의 알 수없는 금액을 제공하고 내가 그들 모두를 선택하려면? 즉

['red','blue','green','purple'] 
# or 
['blue','red'] 

나는 몇 임시 배열을 만든 다음 병합 또는 1로를 평평하게 코드의 혼란에서 일한지,하지만 난 정말 불행입니다.

답변

18

이 시도 :

colors = ['red','blue','green','purple'] 
@items = @items.select { |i| colors.include?(i.color) } 

당신은 또한 현재 위치에서 변경, 대신을 고려하는 것이 좋습니다 : 나는 완전히 당신의 질문을 이해하지만 당신을 위해 일하는 것이 확실하지

@items.reject! { |i| !colors.include?(i.color) } 
+0

굉장, 두 번째는 완벽합니다. –

1

를?

colors_array = ['blue','red','whatever'] 
@items = @items.select {|i| colors_array.include?(i)}