문제

I know how select, collect and map work in Ruby. I was just wondering if there is a similar native Ruby method that can combine them & give results in a single iteration without having the need to remove nil from array?

For ex.

(1..10).map { |x| x*3 if x.even? }.compact
(1..10).select { |x| x.even? }.map{ |x| x*3 }
(1..10).select { |x| x.even? }.collect{ |x| x*3 }

all give same result, which is [6, 12, 18, 24, 30]. But is there 'some_method' gives the same result?

(1..10).some_method { |x| x*3 if x.even? }  ## evaluates to [6, 12, 18, 24, 30]
도움이 되었습니까?

해결책

Enumerable#each_with_object

(1..10).each_with_object([]) { |x,arr| arr.push(x*3) if x.even? }  ## evaluates to [6, 12, 18, 24, 30]

다른 팁

You could use a reduce:

(1..10).reduce([]){ |a,x| a << x*3 if x.even?; a }

or (equivalent, equally confusing):

(1..10).reduce([]){ |a,x| x.even? ? a << x*3 : a }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top