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

Time:06-30

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.

CodePudding user response:

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.

  • Related