我是ruby的新手,我试图从以下哈希中打印出name的输出:
{"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}
这就是我试过的
vm.each do |key, value|
value["name"]
end
我得到了
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>'
我不确定我做错了什么,我试图提取密钥的价值&#34; name&#34;
谢谢
答案 0 :(得分:2)
获取与键关联的值的语法是:
vm["name"]
或者在each
循环中,您已拥有该值。为了说明差异(注意这是很差的代码):
vm.each do |key, value|
if key == "name"
puts value
end
end
答案 1 :(得分:0)
您可以尝试使用select来转换哈希
vm.select{|k,v| v if k=="name"}
但这回归
{"name"=>"nginx-srv1"}
仅获取值
h=vm.select{|k,v| v if k=="name"}
puts h.values
获取价值的最佳方法是使用
vm["name"]