[Ruby] Calculation by extracting elements from an array

A word

Morning activity revival from today Tie yourself up with the rules to stay active in the morning and tweet some morning activities on Twitter

I should continue ... Then the main subject

Calculate by extracting elements from an array

Today's post also challenges the second problem I solved before ... This time, "Add the numbers in the array. However, the same numbers in the array are excluded from the calculation. The same numbers are excluded, so if all the numbers are the same, it will be 0."

• Output example number([3,3,3]) => 0 number([3,2,3]) => 2 number([3,4,3,6,7,9,3,2,5]) => 33

Put it out like this.

So, I thought that I should take out the duplicated elements and add them, and thought "Is it possible to use the uniq method and sum?", But I tried using it, but I could not get the result.

Briefly explain the uniq method

uniq method Suppose you have the following array a = [1,1,1,2,3,4,5,5,5] Use uniq to remove duplicate numbers and return a new array p a.uniq => [1,2,3,4,5]

Reference uniq method official reference

Sure, I was able to remove the duplication, but ... Although the duplicated numbers were neat, one of them remained and they were added together, so the result was not as expected.

``````def number(nums)
new_array=[] #For putting the removed array into a new array

nums.each do |num|
i = 0
nums.each do |n|
if num == n
i += 1
end
end
#①[4,5,4]Then, first of all, "num=4,5,4 "
#The first num is "num=4 and n becomes "n"=4,5,4 "
#Then num is "num"=5 ”and n becomes“ n ”=4,5,4」
#Finally num is "num"=4 and n becomes "n"=4,5,4」
#Counted when num and n are the same number (when they overlap)

if i < 2
new_array << num
end
#If the count of i is 1, the condition is met, so[new_array]Is added to the array.
#If i count is 2, the condition is not met(4 is[i=2]Becomes)

end
sum = 0
new_array.each do |i|
sum += i
end
#new_array Total in array

puts sum #output
end

① number([4,5,4]) => 5
② number([3,4,3,6,7,9,3,2,5]) => 33

``````

I thought about whether it could be made simpler, but I could only think of doing my best and using the sum method for the final calculation.

puts new_array.sum

Like this

I would appreciate it if you could comment if it is easier to put out or if there is another way even if it is not easy.