小包装质量和体积单位转换

 CONVERT_PACKAGE_UNITS =  {
    'mg' =>  1,
    'g'  => 2,
    'kg' => 3,
    'ml' => 4,
    'l'  => 5,
    't'  => 6
  }

  CAPACITY_2_WEIGHT  = {
    4 => 2,
    5 => 3
  }
  # 转换单位, 如果from,to的计量单位不同类型则需要带入密度,否则返回nil
  def convert_unit(_package,from_unit,to_unit,density=nil)
    return _package if from_unit == to_unit
    from_unit = CONVERT_PACKAGE_UNITS[from_unit] if from_unit.is_a?(String)
    to_unit = CONVERT_PACKAGE_UNITS[to_unit] if to_unit.is_a?(String)
    capacity = [4,5]
    weight = [1,2,3,6]

    if density && density > 0 && CAPACITY_2_WEIGHT[from_unit] &&
      capacity.include?(from_unit) && weight.include?(to_unit)
      from_unit = CAPACITY_2_WEIGHT[from_unit]
      _package =  _package * density.to_d
    end

    if density && density > 0 && CAPACITY_2_WEIGHT[to_unit] &&
      weight.include?(from_unit) && capacity.include?(to_unit)
      to_unit = CAPACITY_2_WEIGHT[to_unit]
      _package =  _package / density.to_d
    end

    if (capacity.include?(from_unit) && capacity.include?(to_unit)) ||
      (weight.include?(from_unit) && weight.include?(to_unit))
      from_idx = capacity.index(from_unit) || weight.index(from_unit)
      to_idx = capacity.index(to_unit) || weight.index(to_unit)
      n = 1000.to_d ** (from_idx - to_idx).abs
      if from_idx > to_idx
        return _package * n
      else
        return  _package / n
      end
    end
    nil
  end

猜你喜欢

转载自schooltop.iteye.com/blog/2315889