code_junkie

Uniq by object attribute in Ruby

Nov 11th, 2011
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. YourModel.find(:all, :group => "status")
  2.  
  3. uniq_array = my_array.uniq_by {|obj| obj.id}
  4.  
  5. class Array
  6. def uniq_by(&blk)
  7. transforms = []
  8. self.select do |el|
  9. should_keep = !transforms.include?(t=blk[el])
  10. transforms << t
  11. should_keep
  12. end
  13. end
  14. end
  15.  
  16. class Array
  17. def uniq_by(&blk)
  18. transforms = {}
  19. select do |el|
  20. t = blk[el]
  21. should_keep = !transforms[t]
  22. transforms[t] = true
  23. should_keep
  24. end
  25. end
  26. end
  27.  
  28. class Foo
  29. attr_accessor :foo, :bar, :baz
  30.  
  31. def initialize(foo,bar,baz)
  32. @foo = foo
  33. @bar = bar
  34. @baz = baz
  35. end
  36. end
  37.  
  38. objs = [Foo.new(1,2,3),Foo.new(1,2,3),Foo.new(2,3,4)]
  39.  
  40. # find objects that are uniq with respect to attributes
  41. objs.inject([]) do |uniqs,obj|
  42. if uniqs.all? { |e| Marshal.dump(e) != Marshal.dump(obj) }
  43. uniqs << obj
  44. end
  45. uniqs
  46. end
  47.  
  48. Hash[*recs.map{|ar| [ar[attr],ar]}.flatten].values
  49.  
  50. objs.inject({}) {|h,e| h[e.attr]=e; h}.values
  51.  
  52. h = {}
  53. objs.each {|e| h[e.attr]=e}
  54. h.values
  55.  
  56. class A
  57. attr_accessor :val
  58. def initialize(v); self.val = v; end
  59. end
  60.  
  61. objs = [1,2,6,3,7,7,8,2,8].map{|i| A.new(i)}
  62.  
  63. objs.sort_by{|a| a.val}.inject([]) do |uniqs, a|
  64. uniqs << a if uniqs.empty? || a.val != uniqs.last.val
  65. uniqs
  66. end
Add Comment
Please, Sign In to add comment