John John - 5 months ago 61
Ruby Question

Ruby map and compact methods

I'm working on a program which when given a number "n" will return a factorial (1*2*3...*n) etc. but only the even numbers between 1 and n.

This is the working code that I have now.

def fact_even(n)
arr = (1..n).map {|m| m if m % 2 == 0}
new_arr = arr.compact

The map method is working a bit different than I expected. When given the block it returns a new array which looks like this.

[nil, 2, nil, 4, nil, 6]

I have to use the compact method in the next line in order to get rid of all the nils in the array and then final use inject to get the answer to the factorial.

Is there a way to have map return an array with ONLY the even numbers so I do not have to use compact in the next line?

Otherwise, would there be a more effective way to go about writing a program that does this?

hzm hzm

Try to use select

> (1..20).select { |r| r % 2 == 0}
=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Also, you can try to use reduce for the next line:

> (1..20).select { |r| r % 2 == 0 }.reduce(:*)
=> 3715891200