学习Ruby和API。练习使用Uber API。写了一个脚本来估算乘车的价格。
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
estimate的输出格式为#<Uber::Price:0x00007fc663821b90>
。我运行estimate.class
,它是一个数组。我运行estimate[0].class
并获得Uber::Price
。如何从Uber的API响应中提取我应该获取的值?
发布于 2018-05-30 09:30:27
你是通过一个库与API对话的,通常你会遵循这个库uber-ruby的文档。
不幸的是,该库没有记录Uber::Price
做了什么。可以肯定的是,Uber::Price具有与API文档中相同的字段。Peaking at the code for Uber::Price,我们看到这基本上是正确的。
attr_accessor :product_id, :currency_code, :display_name,
:estimate, :low_estimate, :high_estimate,
:surge_multiplier, :duration, :distance
您可以使用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
发布于 2018-05-30 13:12:58
我是uber-ruby
gem的维护者和合著者。@Schwern是正确的,客户端库提供的属性与uber api响应的结构中的属性相同。我可能应该在文档中指出这一点。
还请注意,gem的测试规范是100%覆盖的,它可以让您了解如何与gem交互,在任何不清楚的地方。
关于价格估算,您可以参考https://github.com/AnkurGel/uber-ruby/blob/master/spec/lib/api/price_estimates_spec.rb#L61-L73
https://stackoverflow.com/questions/50594916
复制相似问题