![](/img/trans.png)
[英]I have a JSON object in my Controller (Ruby/Rails) but i want to access the Json's Object attributes. How to do that
[英]How do I access this hash's object's attributes in Ruby?
我有一个带有 Vehicle 对象的哈希值和一些 Google Maps API 计算:
{#<Vehicle id: 9, type: "hybrid">=>#<GoogleDistanceMatrix::Route origin: #<GoogleDistanceMatrix::Place address: "LAX airport", extracted_attributes_from: {"address"=>"LAX airport"}>, destination: #<GoogleDistanceMatrix::Place address: "Venice Beach", extracted_attributes_from: {"address"=>"Venice Beach"}>, status: "ok", distance_text: "10.4 km", distance_in_meters: 10400, duration_text: "13 mins", duration_in_seconds: 780>}
如何获取Vehicle#type
和GoogleDistanceMatrix#address
(LAX 机场)? 我似乎无法访问它。
似乎您的哈希有一个Vehicle
作为键,而GoogleDistanceMatrix::Route
作为一个值(请注意,它不是您所说的GoogleDistanceMatrix
),因此您可以通过以下方式访问两者:
my_hash.each do |key, val|
puts key.type # => vehicle type
puts val.origin.address # => explanation below on why #origin is needed
end
另请注意, GoogleDistanceMatrix::Route
不直接包含address
属性。 相反,似乎可以通过调用origin
(返回类型为GoogleDistanceMatrix::Place
的对象)然后在结果上调用address
来访问address
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.