0

I have the following Struct

Struct.new("TestClient", :loc, :type, :ssh, :hostname, :ip)
@clients = [
Struct::TestClient.new(1, "mac", true, "test1", "192.168.1.101"),
Struct::TestClient.new(1, "mac", true, "test2", "192.168.1.102"),
Struct::TestClient.new(1, "mac", true, "test3", "192.168.1.103"),
Struct::TestClient.new(1, "mac", true, "test4", "192.168.1.104"),
]

...and I can select the IP addresses into an array based on the type in the following way.

@clients.select{|c| c.type == "mac"}.map(&:ip)
=> ["192.168.1.101", "192.168.1.102", "192.168.1.103", "192.168.1.104"]

Can anyone enlighten me what would that obvious way be to select 2 variables from the Struct into a hash. e.g. I want to select all the ip and hostnames into a hash based on the "mac" type.

I'm expecting the result to look something like this:

["192.168.1.101"=>"test1", "192.168.1.102"=>"test2", "192.168.1.103"=>"test3", "192.168.1.104"=>"test4"]

Thank You!

1 Answer 1

2

You can do as below :

Hash[ @clients.map { |c| [c.ip,c.hostname] if c.type == "mac" }.compact ]

Your structure is not a valid Ruby object, rather you would get from the above code the output as below :

{  
   "192.168.1.101"=>"test1", "192.168.1.102"=>"test2", 
   "192.168.1.103"=>"test3", "192.168.1.104"=>"test4" 
}

Edit

# below will also work
@clients.each_with_object({}) do |c,hash| 
    hash[c.ip] = c.hostname if c.type == "mac"
end
Sign up to request clarification or add additional context in comments.

Comments

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.