문제

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top