Reputation: 12200
I'm new to ruby, and I'm trying to print the output of name from the following hash:
{"id"=>"00fac6ef-ac11-4872-8d9e-3ecf32ae9689", "name"=>"nginx-srv1", "displayname"=>"nginx-srv1", "account"=>"admin", "domainid"=>"f5fed0b0-b8a9-11e4-91c4-464e571bcea9", "domain"=>"ROOT", "created"=>"2015-09-04T12:00:36-0400", "state"=>"Running", "haenable"=>false, "zoneid"=>"60763583-8ab3-436e-8acd-87c783729cdc", "zonename"=>"Toronto", "hostid"=>"d1afc732-ebd6-4e0d-8f81-3e6a0d1f559d", "hostname"=>"TOR-SRV65", "templateid"=>"cbd3ceb0-b615-440e-a0fa-dbcaa234cb8f", "templatename"=>"ubuntu-12.04.4-server-amd64", "templatedisplaytext"=>"ubuntu-12.04.4-server-amd64", "passwordenabled"=>false, "isoid"=>"4c64269d-9a79-4899-9deb-fd39e25dcdd5", "isoname"=>"xs-tools.iso", "isodisplaytext"=>"xen-pv-drv-iso", "serviceofferingid"=>"76d3bacc-eba4-4080-ba72-7c0b524f8027", "serviceofferingname"=>"Large Instance", "diskofferingid"=>"6fec5275-9ec3-4033-8052-b743b3f89303", "diskofferingname"=>"Medium", "cpunumber"=>2, "cpuspeed"=>1000, "memory"=>4096, "cpuused"=>"0.3%", "networkkbsread"=>63023, "networkkbswrite"=>8228, "diskkbsread"=>0, "diskkbswrite"=>0, "diskioread"=>0, "diskiowrite"=>0, "guestosid"=>"f68c9ab2-b8a9-11e4-91c4-464e571bcea9", "rootdeviceid"=>0, "rootdevicetype"=>"ROOT", "securitygroup"=>[], "nic"=>[{"id"=>"c664c0c2-edcf-478e-b1ab-c2b3959f93b6", "networkid"=>"31338f33-5a4c-4d22-b412-f679f9eb7a54", "networkname"=>"VM Network", "netmask"=>"255.255.255.0", "gateway"=>"192.168.10.1", "ipaddress"=>"192.168.10.118", "isolationuri"=>"vlan://3390", "broadcasturi"=>"vlan://3390", "traffictype"=>"Guest", "type"=>"Isolated", "isdefault"=>true, "macaddress"=>"02:00:77:59:00:09"}], "hypervisor"=>"XenServer", "instancename"=>"i-2-32-VM", "tags"=>[], "details"=>{"hypervisortoolsversion"=>"xenserver56"}, "affinitygroup"=>[], "displayvm"=>true, "isdynamicallyscalable"=>false, "ostypeid"=>164}
This is what I have tried
vm.each do |key, value|
value["name"]
end
I get
script.rb:12:in `[]': no implicit conversion of String into Integer (TypeError)
from script.rb:12:in `block in <main>'
from script.rb:11:in `each'
from script.rb:11:in `<main>'
I'm not sure what I'm doing wrong, I'm trying to extract the value of key "name"
Thank you
Upvotes: 0
Views: 54
Reputation: 306
You could try to use select to tranverse the hash
vm.select{|k,v| v if k=="name"}
But this return
{"name"=>"nginx-srv1"}
To get the value only
h=vm.select{|k,v| v if k=="name"}
puts h.values
The best way to obtain values is to use
vm["name"]
Upvotes: 0
Reputation: 13063
The syntax to get the value associated with a key is:
vm["name"]
Or in your each
loop, you already have the value. To illustrate the difference (note that this is poor code):
vm.each do |key, value|
if key == "name"
puts value
end
end
Upvotes: 2