Array#uniq has this behaviour in Ruby 1.9
c = [ "a:def", "a:xyz", "b:abc", "b:xyz", "c:jkl" ]
c.uniq {|s| s[/^\w+/]} #=> [ "a:def", "b:abc", "c:jkl" ]
It can take a block and give unique value with respect to what we give. But, this wont work in Ruby 1.8. How can I create this functionality in ruby 1.8?
Install Marc-André LaFortune's backports gem:
https://github.com/marcandre/backports
That has the block versions of 1.9.2's Array#uniq
and Array#uniq!
. Or if you don't want or need the whole thing, the parts are pretty well isolated so you can pull out just the pieces you need:
https://github.com/marcandre/backports/blob/master/lib/backports/1.9.2/array.rb#L99
It's easy to implement something like:
class Array
def uniq
ret, keys = [], []
each do |x|
key = block_given? ? yield(x) : x
unless keys.include? key
ret << x
keys << key
end
end
ret
end
end