0

I got this array:

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

and i need this as result:

@array = [["1003", "http://www.google.com/2"], ["963", "http://www.google.com/1"]]
  1. Matching every [0] with each other, if it fits set "http: link" to [1].
  2. Delete all entrys with no matching.

How is this possible?

2 Answers 2

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

What this is doing:

Initialize array:

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

Convert to hash:

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

Remove where the value is == "1":

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

Convert back to array:

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

reject is an alias of delete_if

Sign up to request clarification or add additional context in comments.

2 Comments

you need a to_a on the end to match the OP's output.
With an additional to_a at the end so it's in the array format OP asked for.
0

magic!

@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

2 Comments

Thx, this "@links = @array.select { |item| item[1].match(/http/)} " was extremly helpful for me!!
No problems. You could combine that with the top ander and use something like Hash[@array].select{|k,v| v.match(/http/)}.to_a should work :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.