Question

What is the effective way to separate the logic by 2 selections in reduce block ?

i mean, sum if choice equal 1, product if choice equal 2

this is my code but it does not look for if choice equal 2. it works for only choice 1 and the others.

(1..10).reduce(choice == 1 ? :+ : :*)

How can i handle choice 1 and choice 2 in the same reduce block ?

Was it helpful?

Solution

That almost worked. You need:

(1..10).reduce(choice == 1 ? :+ : :*)

Update: it turns out the real issue was the need for an expression template that would not simply default to the scalar product. Apparently throwing an exception (when choice is out of range) is either OK or at least a useful template place-holder. A couple of expressions then come to mind:

(1..10).reduce({1 => :+, 2 => :*}[choice])
(1..10).reduce([nil, :+, :*][choice])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top