(1..10).each_with_object([]) { |x,arr| arr.push(x*3) if x.even? } ## evaluates to [6, 12, 18, 24, 30]
Ruby - Select modified values from array based on some condition
-
02-10-2022 - |
Question
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]
Solution
OTHER TIPS
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 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow