From: Dan Zwell Date: 2007-08-24T14:10:43+09:00 Subject: Re: Combinations of numbers/operators? Donald Patch wrote: > Let's say I have an array consisting of 4 integers i.e. 1,2,3,4. I would > like to print every combination of these numbers using math operators > such as +-/*. The output should resemble something like: > > 1+2+3+4 = 10 > 1+2+3-4 = 2 > 1+2-3-4 = -4 > .... Here's one way to do it--evaluating it would be a lot more complicated without eval(), which is our friend unless we are dealing with user-generated input. for op1 in [:+, :-, :*, :/] for op2 in [:+, :-, :*, :/] for op3 in [:+, :-, :*, :/] expression = "1 #{op1} 2 #{op2} 3 #{op3} 4" puts "#{expression} = #{eval expression}" end end end Dan