返回Ruby中类似的数组元素

时间:2015-11-19 00:53:22

标签: arrays ruby duplicates partial

说我有这样一个数组:

arr = ['footballs_jumba_10', 'footballs_jumba_11', 'footballs_jumba_12',
       'footballs_jumba_14', 'alpha_romeo_11', 'alpha_romeo_12',
       'alpha_juliet_10', 'alpha_juliet_11']

如果我想返回重复项,(假设数组中的任何字符串完全相同,我只会

return arr.detect{ |a| arr.count(a) > 1 }

但是,如果我只想获得数组中每个元素的前10个字符的重复项,而不事先知道变化,该怎么办?像这样:

['footballs_', 'alpha_rome', 'alpha_juli']

3 个答案:

答案 0 :(得分:1)

使用Array#uniq

arr.map {|e| e[0..9]}.uniq
# => ["footballs_", "alpha_rome", "alpha_juli"]

答案 1 :(得分:1)

我在答案here中提出的方法Arry#difference非常简单:

arr << "Let's add a string that appears just once"
  #=> ["footballs_jumba_10", "footballs_jumba_11", "footballs_jumba_12",
  #    "footballs_jumba_14", "alpha_romeo_11", "alpha_romeo_12",
  #    "alpha_juliet_10", "alpha_juliet_11", "Let's add a string that appears just once"]

a = arr.map { |s| s[0,10] }
  #=> ["footballs_", "footballs_", "footballs_", "footballs_", "alpha_rome",
  #    "alpha_rome", "alpha_juli", "alpha_juli", "Let's add "] 
b = a.difference(a.uniq)
  #=> ["footballs_", "footballs_", "footballs_", "alpha_rome", "alpha_juli"] 
b.uniq
  #=> ["footballs_", "alpha_rome", "alpha_juli"] 

答案 2 :(得分:0)

你可以这样做:

def partial_duplicates(elements)
  unique = {}
  duplicates = {}

  elements.each do |e|
    partial = e[0..9]

      # If the element is in the hash, it is a duplicate.
      if first_element = unique[partial]
        duplicates[first_element] = true
        duplicates[e] = true
      else
        # include the element as unique
        unique[partial] = e
      end
  end

  duplicates.keys
end

这将返回唯一的重复项。如果您想要所有重复项,可以使用Array

此外,这将返回每个副本的所有完整表示,因为它似乎更有用,可能是您想要的:

partial_duplicates(arr)
=> ["footballs_jumba_10", "footballs_jumba_11", "footballs_jumba_12", "footballs_jumba_14", "alpha_romeo_11", "alpha_romeo_12", "alpha_juliet_10", "alpha_juliet_11"]

如果您只想要部分重复,可以将条件更改为:

if unique[partial]
  duplicates[partial] = true
else
  unique[partial] = true
end

然后:

partial_duplicates(arr)
=> ["footballs_", "alpha_rome", "alpha_juli"]