Array#uniq with block equivalent in Ruby 1.8.7

2019-02-27 10:02发布

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?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-27 10:06

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

查看更多
来,给爷笑一个
3楼-- · 2019-02-27 10:24

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
查看更多
登录 后发表回答