代码之家  ›  专栏  ›  技术社区  ›  John

行不是用变量中的数据呈现的,而是用数组数据呈现的

  •  2
  • John  · 技术社区  · 8 年前

    我有一个用海图绘制线图的方法。图中的数据是 avg_rates 变量,具有以下值:

    [0.8936e2, 0.8901e2, 0.9015e2, 0.9043e2, 0.8994e2, 0.9105e2, 0, 0, 0, 0, 0, 0]
    

    当我使用变量时,它不会呈现行:

    f.series(
      name: "Average rates",
      data: avg_rates
    )
    

    当我使用数组时,它会渲染线条:

    f.series(
      name: "Average rates",
      data: [0.8936e2, 0.8901e2, 0.9015e2, 0.9043e2, 0.8994e2, 0.9105e2, 0, 0, 0, 0, 0, 0]
    )
    

    我不知道为什么会这样?方法如下:

    def create_avg_rates_chart(avg_rates)
        months = ['jan','feb','mar','apr','mei','jun','jul','aug','sep','okt','nov', 'dec']
        min = avg_rates[0] - 5
        max = avg_rates[0] + 5
    
        avg_rates_chart = LazyHighCharts::HighChart.new('graph') do |f|
          f.chart(type: 'line', height: '150', width: '1000')
          f.pane(size: '100%')
          f.colors(['#0092C9'])
          f.xAxis(
            categories: months.map{ |m| [m] },
            labels: {
              style: { "fontSize": "12px" }
            }
          )
          f.yAxis(
            title: {
                text: 0
            },
            min: min,
            max: max
          )
          f.plotOptions(
            line: {
              dataLabels: {
                  enabled: true,
                  padding: 10
              },
              enableMouseTracking: false,
              lineWidth: 4,
              marker: {
                radius: 5
              }
            }
          )
          f.series(
            name: "Average rates",
            data: avg_rates
          )
          f.legend(enabled: false)
        end
      end
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   3limin4t0r    8 年前

    这很可能是因为当您从数组变量中复制内容时,您不会复制实际对象,而是只复制控制台表示(即 #inspect )

    阵列 avg_rates 最有可能包含 BigDecimal S:

    # avg_rates comes in from outside the function, the line below is a mock.
    avg_rates = %w[89.36 89.01 90.15 90.43 89.94 91.05 0 0 0 0 0 0].map(&:to_d)
    

    这些值在控制台中使用 #检查 方法并生成以下可视化输出:

    #=> [0.8936e2, 0.8901e2, 0.9015e2, 0.9043e2, 0.8994e2, 0.9105e2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    

    这个可视化输出也是完全有效的Ruby代码。但是,如果您键入 0.8936e2 在控制台中,您将实例化一个 Float 而不是一个 大十进制 . 如果您查看只输入数组表示形式的返回值,可以看到这一点:

    avg_rates_repr = [0.8936e2, 0.8901e2, 0.9015e2, 0.9043e2, 0.8994e2, 0.9105e2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    #=> [89.36, 89.01, 90.15, 90.43, 89.94, 91.05, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    

    avg_rates.map(&:class).uniq
    #=> [BigDecimal]
    avg_rates_repr.map(&:class).uniq
    #=> [Float]
    

    如您所说,使用 平均利率 变量,但用于复制表示。这意味着 LazyHighCharts::HighChart 不接受 大十进制 但是接受 浮标 因此,您的解决方案应该是将值转换为 浮标 在把它们传给 :data 选择 #series

    data: avg_rates.map(&:to_f)