I need to count the duplicates, they need to be 100% identical to increase my count, but I can not use a nothing out of Ruby 1.8.5, this code will run inside a plugin in google sketchup
Google Sketchup Ruby API
puts VERSION
1.8.5
puts RUBY_PLATFORM
i686-darwin8.10.1
product = 'Glass'
x = width
y = length
z = density
product_list = [
{ "product" => 1, "x" => 200, "y" => 100, "z" => 18},
{ "product" => 1, "x" => 200, "y" => 100, "z" => 18},
{ "product" => 1, "x" => 300, "y" => 100, "z" => 18},
{ "product" => 2, "x" => 300, "y" => 100, "z" => 18},
{ "product" => 2, "x" => 100, "y" => 100, "z" => 18},
{ "product" => 2, "x" => 100, "y" => 100, "z" => 18},
{ "product" => 3, "x" => 100, "y" => 100, "z" => 18}
];
product_list_result = product_list.count_duplicate();
product_list_result = [
{ "product" => 1, "x" => 200, "y" => 100, "z" => 18, "count" = 2},
{ "product" => 1, "x" => 300, "y" => 100, "z" => 18, "count" = 1},
{ "product" => 2, "x" => 300, "y" => 100, "z" => 18, "count" = 1},
{ "product" => 2, "x" => 100, "y" => 100, "z" => 18, "count" = 2},
{ "product" => 3, "x" => 100, "y" => 100, "z" => 18, "count" = 1}
];
dup
is for to not modify originalproduct_list
Tested in
ruby 1.8.7
Short answer:
Longer answer explaining how this works. Starting with your data:
Now you have a hash with products as keys, and counts as values:
Now convert it to the array format you desire:
Which results in:
The array conversion can be done more succinctly:
h.keys returns an array of keys from hash h, which is just the unique products in your list. The function map then replaces each object in that array with the result of the block that follows which simply adds the count value to the product hash.