In Ruby, uniq is great for clearing duplicate values from an Array. However it clears every duplication throughout the array, no matter where it is located.
irb(main):001:0> a = [1,1,1,3,3,5,7,7,7,7,7,1,1,1,3,3,3]
=> [1, 1, 1, 3, 3, 5, 7, 7, 7, 7, 7, 1, 1, 1, 3, 3, 3]
irb(main):002:0> a.uniq
=> [1, 3, 5, 7]
That's not what I want. I want the data locally uniq-ed, so that I'd get [1, 3, 5, 7, 1, 3] as if each contigous block of data were shrinked to exactly one element.
require 'pp'
a, b = [1,1,1,3,3,5,7,7,7,7,7,1,1,1,3,3,3], []
a.each {|x| if a[x]!=b.last then b.push(a[x]) end}
pp b
This operation won't destroy 'a' therefore the a.each... line cannot be executed more than once without first clearing the target array, as it would push the data again into 'b'.
Update: Shoot! Enumerable#chunk - introduced in Ruby 1.9.2 - just does the same, so it is no use to reinvent the wheel.
Utolsó kommentek