最近写ruby,用到hash,通过k去获取v值,有时候通过hash["k"]去获取可以获取到,有时候通过又获取不到,感觉一脸懵逼

 

仔细观察了下ruby的hash,有两种表现形式,所以获取v值也有两种形式

方式1

hash["k"]

 

方法2

hash[:k]

 

下面看下具体的代码,大家在获取ruby的hash的时候要注意

s = '{"success":1,"data":"UPID:host-5853c035138f:00002954:DD16:5D37BC34:add disk::admin@vtp:"}'
hash_s = JSON.parse(s)

puts hash_s
# {"success"=>1, "data"=>"UPID:host-5853c035138f:00002954:DD16:5D37BC34:add disk::admin@vtp:"}
puts hash_s["data"]
# UPID:host-5853c035138f:00002954:DD16:5D37BC34:add disk::admin@vtp:
puts hash_s[:data]
# 这里是空


hash_h = {"success":1,"data":"UPID:host-5853c035138f:00002954:DD16:5D37BC34:add disk::admin@vtp:"}
puts hash_h
# {:success=>1, :data=>"UPID:host-5853c035138f:00002954:DD16:5D37BC34:add disk::admin@vtp:"}
puts hash_h["data"]
# 这里是空
puts hash_h[:data]
# UPID:host-5853c035138f:00002954:DD16:5D37BC34:add disk::admin@vtp:

 

posted on 2019-07-24 10:51  bainianminguo  阅读(652)  评论(0编辑  收藏  举报