ruby 哈希中的条件设置值

Conditional set value in a ruby hash

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

由于商店的纬度和经度可以是nil,我想测试一下我的散列中计算的值是return是否应该是这样的字符串: "no precision address".

我写了这个方法,效果很好,仍然只有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

怎么样?

  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 开始并且字符串被设置为值。

基于 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