I have an array of fully qualified domain names:
["filer1.abc.com", filer2.abc.com, filer3.xyz.com]
I have another array that has hostnames:
["filer1", "filer3"]
I have to compare the two arrays, and if the hostnames are present in fqdn, then I need to get the fqdn from the first array. For example, "filer1"
is present in "filer1.abc.com"
, so I need to get the value "filer1.abc.com"
. And "filer3"
is present in "filer3.xyz.com"
, so I need to get the value "filer3.xyz.com"
.
Help is appreciated.
["filer1.abc.com", filer2.abc.com, filer3.xyz.com].map.each_with_index {|vserver, indx| vserver.id.include? host_names[indx] unless host_names[indx].nil?}}
I get [true, nil, nil, nil]
, but I actually need the values of fqdn like ["filer1.abc.com"]
.
fqdn_array = ["filer1.abc.com", "filer2.abc.com", "filer3.xyz.com"]
hostnames = ["filer1", "filer3"]
result = fqdn_array.keep_if{|fqdn| (hostnames - fqdn.split('.')).length < hostnames.length}
# => ["filer1.abc.com", "filer3.xyz.com"]
Array#keep_if
iterates through the array and keeps all elements where the block is true. In the block I split your fqdn at the dot into an array. Then I subtract it from the hostnames array. If the result is shorter than the original array length, I found a fqdn which includes one of your hostnames and the condition returns true.