首页 > 解决方案 > Ruby API response - how to action

问题描述

Learning Ruby & APIs. Practicing with the Uber API. Wrote a script to estimate the price of a ride.

require 'uber'
require 'geocoder'

def ride()

    # print "start? "
    # location_start = gets.chomp
    # print "finish? "
    # location_end = gets.chomp

    coordinates_start = Geocoder.coordinates("dublin") # gets a location for start and transforms into lat long
    coordinates_end = Geocoder.coordinates("dalkey") # gets a location for start and transforms into lat long

    client = Uber::Client.new do |config|
      config.server_token  = "{SERVER_TOKEN}"
      config.sandbox       = true
    end
    estimate = client.price_estimations(start_latitude: coordinates_start[0], start_longitude: coordinates_start[1],
                             end_latitude: coordinates_end[0], end_longitude: coordinates_end[1])
    estimate

end

puts ride

the output of estimate has the format #<Uber::Price:0x00007fc663821b90>. I run estimate.class and it's an array. I run estimate[0].class and I get Uber::Price. How can I extract the values that I should be getting from Uber's API response? [0]

[0] https://developer.uber.com/docs/riders/references/api/v1.2/estimates-price-get#response

标签: ruby

解决方案


您正在通过库与 API 交谈,通常您会遵循该库uber-ruby的文档。

不幸的是,该库没有记录 an 的Uber::Price作用。可以肯定的是,Uber::Price 具有与 API 文档中相同的字段。在 Uber::Price 的代码中达到顶峰,我们看到这基本上是正确的。

attr_accessor :product_id, :currency_code, :display_name,
              :estimate, :low_estimate, :high_estimate,
              :surge_multiplier, :duration, :distance

您可以使用 访问 API 字段estimate.field。例如,要查看所有估计和持续时间...

estimates = ride()

estimates.each do |estimate|
    puts "Taking a #{estimate.display_name} will cost #{estimate.estimate} #{estimate.currency_code} and take #{estimate.duration / 60} minutes"
end

推荐阅读