0

I'm trying to merge two arrays when there is a key match.

"mac" array should match "id[0]" key, and if match is true append "id[1]" value to my "ip".

For this example will use "computer", "ip address" and "mac address"

id = {
  '01:02:03:04:05:06' => 'Desktop'
  '07:08:09:10:11:12' => 'Laptop'
}

ip = { '192.168.0.10', '192.168.0.20' }
mac = { '01:02:03:04:05:06', '07:08:09:10:11:12' }

Code I'm using so far;

net = ip.zip(mac)
net.each do |ip,mac|
  puts "#{ip} / #{mac}"
end

Example output (wanted):

192.168.0.10 / 01:02:03:04:05:06 / Desktop
192.168.0.20 / 07:08:09:10:11:12 / Laptop
1
  • Tux, a few observations: 1. ip and mac are arrays, so enclose with [], not {} (plz edit); 2. it is confusing to give the (local-to-) block variables the same names as the arrays ip and mac; 3. you could chain to avoid the need for the temporary variable net (i.e., ip.zip(mac).each {|i,m| puts ... }); 4. elements of a hash cannot be identified with indices (id[0] is the value corresponding to key 0, or nil if there is no key 0), so instead say something like, "for a given element m of mac, if id contains an element with key m, then append id[m] to...". Commented Nov 12, 2013 at 18:28

1 Answer 1

2

In your example id (rename it to hostnames) is a Hash and not an Array, thus you can look up on the fly and change the line with puts to:

puts "#{ip} / #{mac} / #{id[mac]}"

Not sure if that matches your question and requirements. If so, please change the question title (hash lookup).

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

2 Comments

I'll rename it to "host" but your example worked :-) Thank you!
I was momentarily confused until it clicked that you were replacing just one line of the questioner's code. Depending what "if there is a match" means, maybe puts "#{ip}" + (id[mac] ? " / #{mac} / #{id[mac]}" : "").

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.