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

标准化两个哈希以包含相同的键

  •  0
  • chris  · 技术社区  · 6 年前

    我希望在highcharts图形中绘制多个系列。我有以下两个变量

       first = {5 => [dates in here], 6 => [dates in here], etc}
       second = {4 => [dates in here], 5 => [dates in here], etc}
    

    键是与月份(4月、4月、5月、5月等)相关的数字

    我遇到的问题是,这两个哈希值可能并不总是具有相同的对应月份。因此,当我绘制数据时,第一个(5)在第二个(4)旁边绘制,第一个(6)在第二个(5)旁边绘制,以此类推。

    如何标准化这两个变量,使它们始终包含相同的键,即使看起来像这样:

       first = {4 => [no data], 5 => [dates in here], 6 => [dates in here], etc}
       second = {4 => [dates in here], 5 => [dates in here], 6 => [no data], etc}
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   Nermin    6 年前
    first_keys = first.keys
    second_keys = second.keys
    keys = first_keys + second_keys
    
    keys.uniq.each do |key|
      first[key]  = [] if first[key].nil?
      second[key] = [] if second[key].nil?
    end
    
        2
  •  1
  •   Eli Sadoff    6 年前

    有很多方法可以做到这一点,因为它是相当开放的,但您可以创建一个 keys 从两个哈希中提取数组,并迭代该赋值 nil 到散列在那 key .我会这样做

    keys = (first.keys + second.keys).uniq
    keys.each do |key|
      first[key] ||= nil
      second[key] ||= nil
    end
    
        3
  •  0
  •   Cary Swoveland    6 年前

    当您绘制数据时,大概x轴上有个月,y轴上有天,我认为最方便的方法是迭代一系列的月,以提供两个哈希中包含的键(月)的最小覆盖范围。

    data = [{ 5=>[3, 5, 11, 24], 6=>[1, 7, 13, 30], 2=>[4, 13, 18, 29] },
            { 4=>[6, 9, 19, 26], 5=>[4, 8, 11, 22], 1=>[1, 19, 22, 24] }]
    
    month_range = Range.new(*data.reduce([]) { |arr, h| arr | h.keys }.minmax)
      #=> 1..6
    

    笔记

    a = data.reduce([]) { |arr, h| arr | h.keys }
      #=> [5, 6, 2, 4, 1]
    b = a.minmax
      #=> [1, 6]
    Range.new(*b)
      #=> Range.new(*[1, 6]) => Range.new(1, 6) => 1..6
    

    我将输入表示为任意哈希数组,如果有两个以上的哈希。

    对于绘图,只需在 month_range ,然后每月 m 迭代元素 h 属于 data (哈希)其中 H 有钥匙 M ,并在中绘制日期 h[m] ,如果有(不是“无数据”)。

    month_range.each do |m|
      data.each do |h|
        <plot h[m]> if h.has_key?(m) && h[m].any?
      end
    end