参数阵列#uniq的(即,uniq_by) [英] Parameterized Array#uniq (i.e., uniq_by)

查看:193
本文介绍了参数阵列#uniq的(即,uniq_by)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果不是从一个数组删除重复的元素,我想删除有一个共同的特定属性的元素是什么?

What if instead of removing duplicate elements from an array, I want to remove elements that have a specific property in common?

具体来说,我想从数组中删除所有的字符串重复的精华,其中的本质是这样定义的:

Specifically, I want to remove all strings from an array with duplicate "essences", where essence is defined like this:

class String
  def essence
    downcase.gsub('&', 'and').gsub(/[^a-z0-9]/, '')
  end
end

我想是这样的:

['a', 'A', 'b'].uniq_by(&:essence)
# => ['a', 'b'] (or ['A', 'b']; I don't really care)

什么是实现这一目标的最佳方式?

What's the best way to accomplish this?

推荐答案

的ActiveSupport有阵列#uniq_by 的,这是code:

Activesupport has a Array#uniq_by, and this is the code:

class Array
  def uniq_by
    hash, array = {}, []
    each { |i| hash[yield(i)] ||= (array << i) }
    array
  end
end

刻面也有一个可枚举#uniq_by

module Enumerable    
  def uniq_by
    h = {}
    inject([]) {|a,x| h[yield(x)] ||= a << x}
  end    
end

这篇关于参数阵列#uniq的(即,uniq_by)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆