[Ruby] Get unique elements from an array

Overview

I wrote a program to get and calculate non-overlapping elements in an array. If you want something that is duplicated, you can get it by changing the description of the comparison operator. I would appreciate it if you could point out any mistakes in the recognition.

table of contents

--Practice --Problem --Answer

--References

Practice

problem

Create a method that outputs the sum of any three numbers. However, if the same number is included, it is not counted.

answer

The hash is generated first because we want to calculate the number of elements and use select to get the one that meets the conditions.

def uniq_num(ary)
  counts = Hash.new(0)                             #Generate hash
  ary.each { |v| counts[v] += 1 }                  #Search for duplicate elements
  i = counts.select { |v, count| count == 1 }.keys #Get only non-duplicates
  p i.sum                                          #Output total
end

#Method call
uniq_num([1, 2, 3])
uniq_num([3, 2, 3])
uniq_num([3, 3, 3])

#Terminal output result

# 6
# 2
# 0

References

-Ruby 3.0.0 Reference Manual (Hash.new) -Ruby 3.0.0 Reference Manual (filter) -Remove duplicate elements from Ruby array -[How can I efficiently extract repeating elements in a Ruby array? Duplicate

Recommended Posts

[Ruby] Get unique elements from an array
[Ruby] Calculation by extracting elements from an array
[Ruby] Get array elements alternately.
[Java] Get a random value from an array
[Ruby] Searching for elements in an array using binary search
[Ruby] Array
Get "2-4, 7, 9" from [4, 7, 9, 2, 3]
Send an email from gmail with Ruby
Compare the elements of an array (Java)
Sort an array of Ruby homebrew classes
[Swift] Summary of how to remove elements from an array (personal note)
[Swift] How to get the number of elements in an array (super basic)
[Java] Program example to get the maximum and minimum values from an array
Ruby two-dimensional array
Ruby array manipulation
Be careful when deleting multiple elements from an array etc. with a for statement
Examine the elements in the array using the [Ruby] includes? Method
How to output standard from an array with forEach
[Ruby] How to extract a specific value from an array under multiple conditions [select / each]
Create path from array
[Ruby] Count an even number in an array using the even? Method
How to change a string in an array to a number in Ruby
[For Ruby beginners] Explain how to freely delete array elements!
How to retrieve the hash value in an array in Ruby
Easily get an integer from a system property in Java
Get attributes and values from an XML file in Java
Generate Stream from an array of primitive types in Java
Get a non-empty collection from an Optional stream in java
[Ruby] How to batch convert strings in an array to numbers
I tried to create an API to get data from a spreadsheet in Ruby (with service account)