Tux
Tux

Reputation: 247

Add Array Value from Array1 if Key Matches in Array2 (Ruby)

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

Upvotes: 0

Views: 121

Answers (1)

Felix
Felix

Reputation: 4716

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).

Upvotes: 2

Related Questions