简体   繁体   中英

How do I access this hash's object's attributes in Ruby?

I have a hash with a Vehicle object and some Google Maps API calculations:

{#<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>}

How do I get the Vehicle#type and GoogleDistanceMatrix#address (LAX airport)? I can't seem to access it.

It seems like your hash has a Vehicle as a key and GoogleDistanceMatrix::Route as a value (note it's not a GoogleDistanceMatrix as you said), therefore you could access both with something like this:

my_hash.each do |key, val|
  puts key.type # => vehicle type
  puts val.origin.address # => explanation below on why #origin is needed
end

Also note that GoogleDistanceMatrix::Route does not contain an address property directly. Rather, address seems to be accessible by calling origin (which returns an object of type GoogleDistanceMatrix::Place ) and then address on the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM