簡體   English   中英

如何在 Ruby 中訪問此哈希對象的屬性?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM