数组元素的匹配困难

时间:2012-01-06 17:28:07

标签: ruby-on-rails ruby

我得到了这个数组:

@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. 删除所有没有匹配的商家。
  3. 这怎么可能?

2 个答案:

答案 0 :(得分: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

的别名

答案 1 :(得分: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