我得到了这个数组:
@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"]]
这怎么可能?
答案 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