Array#uniq with block equivalent in Ruby 1.8.7

假装没事ソ 提交于 2019-12-04 04:28:21

问题


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?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/8653508/arrayuniq-with-block-equivalent-in-ruby-1-8-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!