2012-01-06 141 views
0

我得到这个阵列的难匹配:数组元素

@array = [["1003", "4"], ["963", "3"], ["1006", "1"], ["1064", "1"], ["1095", "1"], ["963", "http://www.google.com/1"], ["1003", "http://www.google.com/2"]] 

,我需要这个作为结果:

@array = [["1003", "http://www.google.com/2"], ["963", "http://www.google.com/1"]] 
  1. 匹配每[0]彼此,如果它符合一套“ http:link“链接到[1]。
  2. 删除所有没有匹配的entrys。

这怎么可能?

回答

8
Hash[@array].reject{|k,v| v == "1"}.to_a 

这是什么做的:

初始化数组:

@array => [["1003", "4"], ["963", "3"], ["1006", "1"], ["1064", "1"], ["1095", "1"], ["963", "http://www.google.com/1"], ["1003", "http://www.google.com/2"]] 

转换为哈希:

hash = Hash[@array] => {"1003"=>"http://www.google.com/2", "963"=>"http://www.google.com/1", "1006"=>"1", "1064"=>"1", "1095"=>"1"} 

删除其中的值是== “1”:

hash = hash.reject!{|k,v| v == "1"} => {"1003"=>"http://www.google.com/2", "963"=>"http://www.google.com/1"} 

转换回阵列:

hash.to_a => [["1003", "http://www.google.com/2"], ["963", "http://www.google.com/1"]] 

拒绝是delete_if

+0

你需要一个'to_a'来匹配OP的输出。 – iain 2012-01-06 17:55:25

+0

最后还有一个'to_a',因此它是OP所要求的数组格式。 – 2012-01-06 17:57:27

+0

你让我的一天,thx很多! – 2012-01-09 09:04:23

0

神奇的别名!

@array = [["1003", "4"], ["963", "3"], ["1006", "1"], ["1064", "1"], ["1095", "1"], ["963", "http://www.google.com/1"], ["1003", "http://www.google.com/2"]] 

@links = @array.select { |item| item[1].match(/http/)} 
@non_links = @array - @links 
@non_links.map do |non_link| 
    if @links.map(&:first).include? non_link.first 
    [non_link.first, @links.select { |link| link.first == non_link.first }.first.last] 
    end 
end.compact 
+0

这是一段漫长的魔术。 – 2012-01-06 17:57:55

+1

我怪奶酪! – 2012-01-06 17:59:13

+0

Thx,这个“@links = @ array.select {| item | item [1] .match(/ http /)} ”对我极其有用! – 2012-01-09 09:04:00