Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array subtraction?

Tags:

arrays

ruby

Either I don't understand what happens when you subtract an array from an array, or something is wrong here.

What I have is a list of usernames (strings) in an array:

users.count - users.uniq.count    # => 9
users - users.uniq                # => []

I'm not sure how this is possible.

I'm essentially trying to find a list of the duplicates. I realize there are other ways to go about this, just trying to understand Array operations better.

Here is the workaround code I used to get the same:

users.inject(Hash.new(0)) {|h,i| h[i] += 1; h}.select{|k,v| v > 1}
like image 294
BaroldGene Avatar asked Apr 25 '26 22:04

BaroldGene


1 Answers

You could use

dups = users.select{|e| users.count(e) > 1 }.uniq

Or, to find only a single duplicate element:

firstDup = users.detect {|e| users.count(e) > 1 }

About the array subtraction, this may clarify:

a = [1, 1, 1, 1, 1]
a - [1] # => []

Array subraction removes all occurences, not just one.

like image 189
tckmn Avatar answered Apr 27 '26 10:04

tckmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!