首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Ruby API响应-如何操作

Ruby API响应-如何操作
EN

Stack Overflow用户
提问于 2018-05-30 08:50:33
回答 2查看 61关注 0票数 2

学习Ruby和API。练习使用Uber API。写了一个脚本来估算乘车的价格。

代码语言:javascript
复制
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响应中提取我应该获取的值?

0

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-30 09:30:27

你是通过一个库与API对话的,通常你会遵循这个库uber-ruby的文档。

不幸的是,该库没有记录Uber::Price做了什么。可以肯定的是,Uber::Price具有与API文档中相同的字段。Peaking at the code for Uber::Price,我们看到这基本上是正确的。

代码语言:javascript
复制
attr_accessor :product_id, :currency_code, :display_name,
              :estimate, :low_estimate, :high_estimate,
              :surge_multiplier, :duration, :distance

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

代码语言:javascript
复制
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
票数 3
EN

Stack Overflow用户

发布于 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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50594916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档