1

I have an array of hashes where each hash contains a handful of keys. I want to check to see if any number of the hashes have the same user_id.

An example would look like this:

[ {:id => 1, :user_id => 2, :location => nil, :facility_id => nil}
  {:id => 3, :user_id => 2, :location => 'China', :facility_id => 20} ]

I would need this to return true in this case, where two of the hashes have a user_id in common. How do I do this the 'ruby way'?

2 Answers 2

4
arr = [ {:id => 1, :user_id => 2, :location => nil, :facility_id => nil},
  {:id => 3, :user_id => 2, :location => 'China', :facility_id => 20} ]
p arr != arr.uniq{|u| u[:user_id]} #=> true
Sign up to request clarification or add additional context in comments.

3 Comments

My idea was almost the same but one note - comparing the sizes should be enough. Comparing the whole arrays will be slower.
@izomorphius Ruby seems to optimize for this (line 1463). But generally speaking, you are right.
this optimization works only for the false case. Imagine you have an array with 10 hashes with different user_id-s and each hash has a size of hundreds of megabytes.
3

Try this:

a.map{|t| t[:user_id]}.uniq.size == a.size

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.