How can I find unique values in an array.
For instance:
my_array = [2,4,4,5,5,7]
In the above array are two unique values 2 and 7 and I would like to know either a self defined or other method to assign these unique values to variables.
Use array.group_by.
my_array.group_by{|v| v}.delete_if{|k,v| v.length > 1}.keys
or alternatively
my_array.group_by{|v| v}.select{|k,v| v.length == 1}.keys
This is a bit leggy, perhaps, but gets the job done
my_array.each_with_object(Hash.new(0)){|x,h| h[x] += 1}.select{|k,v| v == 1}.keys
myarray.select { |n| myarray.count(n) == 1 }? I'm assuming it might be faster?
arr.uniq.select { |n| arr.count(n) == 1 }would be an improvement to my earlier suggestion, though still not as performant as the answers given so far.