红宝石哈希中的条件设置值

时间:2018-12-06 11:38:49

标签: ruby-on-rails ruby haversine

我正在使用Haversine gem计算站点与商店之间的距离。

由于商店的纬度和经度可以为nil,因此我想测试是否是这种情况,在我的哈希中要返回的值应该是这样的字符串:“无精确地址”

我编写了此方法,它运行良好,但仍然只有nil地址的点:

    require 'haversine'

    class Api::V1::Angular::SitesController < Api::ApplicationController

    # GET /api/v1/angular/sites/:id/distances
      def stores_distances
        site      = Site.find params[ :id ]
        distances = Store.current.map do |store|
          {
            name: store.name,
            value: Haversine.distance(
                    site.address.latitude,
                    site.address.longitude,
                    store.address.latitude,
                    store.address.longitude
                  ).round(2)
          }
        end

        render json: {
          distances: distances.to_json
        }
      end
end

2 个答案:

答案 0 :(得分:1)

基于Dave评论:

  def stores_distances
    site      = Site.find params[ :id ]
    distances = Store.current.map do |store|
      {
        name: store.name,
        value: distance(site.address, store.address) || 'no precision address'
      }
    end

    render json: {
      distances: distances.to_json
    }
  end
  def distance(site_address, store_address)
     return nil unless store_address.latitude && store_address.longitude
     Haversine.distance(
       site_address.latitude,
       site_address.longitude,
       store_address.latitude,
       store_address.longitude
     ).round(2)
  end

答案 1 :(得分:0)

怎么样?

  def stores_distances
    site      = Site.find params[ :id ]
    distances = Store.current.map do |store|
      value = Haversine.distance(
        site.address.latitude,
        site.address.longitude,
        store.address.latitude,
        store.address.longitude
      ).round(2) || 'no precision address'

      {
        name: store.name,
        value: value
      }
    end

    render json: {
      distances: distances.to_json
    }
  end

当您的Haversine.distance为nil时,OR会踢入,并将字符串设置为值。