I am trying to create a ruby program where three numbers are entered and their sum is taken but if any numbers are the same they don't count toward the sum. example (4,5,4) = 5 My problem is with my expressions. If i enter the same number I get multiple output for various combination. example enter 5,5,5 = 15,5,0
if a != b or c then
puts a+b+c
elsif b != a or c then
puts a+b+c
elsif c != a or b then
puts a+b+c
end
if a == b then
puts c
elsif a == c then
puts b
elsif b == c then
puts a
end
if a == b and c then
puts 0
elsif b == a and c then
puts 0
elsif c == a and b then
puts 0
end
Solving it with two beautiful self explanatory one-liners
array = [a,b,c]
array = array.keep_if {|item| array.count(item) == 1 }
array.inject(0){|sum,item| sum + item}
-The first line creates an array with your parameters.
-The second line only keep the items whose count equals to 1 (remove the ones that appear more than one time), and store that on the array.
-The third line sums all the remaining elements.
Voilà, the ruby way :)
array.inject(0, :+)
. This has two advantages IMO: 1) you can tell it's only adding, and not doing anything else, much more quickly 2) it has a cute emoticon - Andrew Grimm 2012-04-04 00:05
Enumerable#group_by
followed byEnumerable.select
and #3 can be done withEnumerable#reduce
. - NoName 2012-04-03 22:40