通过Google Maps API,我获得了两个地点之间的所有路线选择:
url = http://maps.googleapis.com/maps/api/directions/json?origin=rodovia-helio-smidt-s-n-cumbica-guarulhos+Brasil&destination=rua-coronel-diogo-814-jardim-da-gloria-sao-paulo+Brasil&alternatives=true&sensor=false
现在我想找到最短的距离。所以我必须遍历所有路由,将每个距离写入一个新数组,然后从这个新数组中获取最小值:
uri = URI(url)
response = Net::HTTP.get(uri)
responseJson = JSON.parse(response)
routes = responseJson['routes']
distances = Array.new
routes.each do |route|
distances.push(route['legs'][0]['distance']['value'])
end
shortest = distances.min
这很有效,但我想知道是否有更优雅的方式使用may& map或类似的东西。
答案 0 :(得分:1)
你可以这样做:
distances = responseJson['routes'].map { |r| r['legs'][0]['distance']['value'] }
shortest = distances.min
或者,如果你喜欢一行中的所有内容:
shortest = responseJson['routes'].map { |r| r['legs'][0]['distance']['value'] }.min
完整的代码如下所示:
uri = URI(url)
response = Net::HTTP.get(uri)
responseJson = JSON.parse(response)
distances = responseJson['routes'].map { |r| r['legs'][0]['distance']['value'] }
shortest = distances.min