user3033493
user3033493

Reputation: 53

Remove duplicates from loop

i have following code.

for i in 0..sold.length-1
    duplicate = sold[i]
    print duplicate.check_duplicates
    print "     "
    print sold[i].lotnumber + "\t"

    print sold[i].serialnumber

end

this will print

 1     29371    43
 1     13797    6
 1     08114    55
 1     70657    106
 1     32741    74
 2     07272    103
 2     07272    103
 1     37416    14
 1     05153    177
 1     54338    115
 3     74522    171
 3     74522    171
 3     74522    171

How can i remove the duplicates (3 74522 171 and 2 07272 103) so there is only 1 of each?

Upvotes: 0

Views: 117

Answers (3)

usha
usha

Reputation: 29349

uniq_solds = sold.collect{|s| [s.check_duplicates, s.lotnumber, s.serialnumber]}.uniq

uniq_solds.each do |s|
  p s.join("      ")
end

Upvotes: 2

steenslag
steenslag

Reputation: 80065

The hash resulting from the group_by method can be used as a counting device; this does not use the check_duplicates method.

grouped = sold.group_by{|item| [item.lotnumber, item.serialnumber]}
grouped.each{|key, value| puts "#{value.size}   #{key.first}\t#{key.last}"}

Upvotes: 1

cogle
cogle

Reputation: 1079

You can try using something called uniq!, here is a link to the API.

http://www.ruby-doc.org/core-2.0.0/Array.html#method-i-uniq-21


Upvotes: 0

Related Questions