[英]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.