views:

100

answers:

2

Working with the following code, I need to return only records where the `point' attribute is unique. I can't seem to get there by myself.

uniques = Item.find_all_by_item_id(item_id)
uniques.sort! {|a, b| b.point <=> a.point } # how do I reject the equal points?

In other words.. I guess, how do you make [0, 1, 1, 1, 2, 3, 3, 4, 4, 7] #=> [0, 2, 7] ?

+1  A: 

How about this:

# Get the number of items with each point value
counts = Item.count("point", :group => "point")

# Get the IDs of all entries that only show up once
unique_ids = counts.collect { |count| count[0] if count[1] == 1 }.compact

unique_items = Item.find_all_by_id(unique_ids)
spilth
...find_all_by_point --rather?
Jesse
You are the Egg-man, you are the Walrus. Thank you :-)
Jesse
I think find_all_by_id is what you want... at least that's what worked in my own Rails app. I was looking at an integer field in mine.
spilth
find_all_by_point works for me. by_id seems to return only []
Jesse
Feel free to update my answer or comment with the final code so I can update it.
spilth
+1  A: 

I can think of few ways off the top of my head to do this:

uniques.reject!{|u| uniques.select{|x| x == u}.size > 1}

Basically iterate through the uniques array and then see if there is more than one of those items in the array. Obviously there are lots of clever ways to speed this up, but for small arrays this should work.

or

h = Hash.new(0)
uniques.each{|u| h[u] += 1}
h.reject{|k,v| v > 1}.keys

Basically count how many times each item shows up in a hash, if its more than one reject it and then just look at the keys.