如果没有给出值,则使用nil值填充哈希值

时间:2017-04-05 06:41:59

标签: ruby magic-square ruby-hash

我有这些数组:

positions = [[0, 1, 2], [2, 3]] 
values = [[15, 15, 15], [7, 7]]
keys = [1, 4]

我需要创建一个哈希,其密钥来自keys,值来自values。值必须在positions. If no index is defined, nil`中定义的索引处应添加到该索引中。

三个数组包含相同数量的元素; keys有两个元素,values两个,positions两个元素。所以没关系。

预期产出:

hash = {1=>[15, 15, 15, nil], 4=>[nil, nil, 7, 7]}

4 个答案:

答案 0 :(得分:2)

让拉链开始(回答原始问题):

row_size = positions.flatten.max.next

rows = positions.zip(values).map do |row_positions, row_values|
  row = Array.new(row_size)
  row_positions.zip(row_values).each_with_object(row) do |(position, value), row|
    row[position] = value
  end
end

keys.zip(rows).to_h # => {1=>[15, 15, 15, nil], 4=>[nil, nil, 7, 7]}

答案 1 :(得分:1)

不是最干净但是有效:P

max = positions.flatten.max + 1
pv = positions.zip(values).map { |o| o.transpose.to_h }
h = {}
pv.each_with_index do |v, idx|
  h[keys[idx]] = Array.new(max).map.with_index { |_, i| v[i] }
end

# h
# {1=>[15, 15, 15, nil], 4=>[nil, nil, 7, 7]}

或者如果你更喜欢压缩程度更高但可读性更差的人......

keys.zip(positions.zip(values).map { |o| o.transpose.to_h }).reduce({}) do |h, (k, v)|
  h[k] = Array.new(max).map.with_index { |_, i| v[i] }
  h
end

答案 2 :(得分:1)

出于好奇:

nils = (0..positions.flatten.max).zip([nil]).to_h
keys.zip(positions, values).group_by(&:shift).map do |k, v|
  [k, nils.merge(v.shift.reduce(&:zip).to_h).values]
end.to_h
#⇒ {1=>[15, 15, 15, nil], 4=>[nil, nil, 7, 7]}

答案 3 :(得分:0)

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: getDaysInMonth(currentMonth, currentYear),
    datasets: [{
      label: '# new leads created',
      data: getLeadsForMonth(currentMonth, currentYear),
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  },
  maintainAspectRatio: false
});

function getDaysInMonth(month, year) {
  var date = new Date(year, month, 1);
  var dates = [];
  while (date.getMonth() === month) {
    var currentDate = new Date(date).toISOString().replace(/T.*/, '').split('-').reverse().join('-');
    var catDate = currentDate.replace(/-2017/g, '').replace(/-/g, '/').split('/').reverse().join('/');;
    dates.push(catDate);
    date.setDate(date.getDate() + 1);
  }
  return dates;
}

function getLeadsForMonth(month, year) {

  // Create empty array to put leadCount in
  var leadsPerDay = new Array();

  /* Use $http.get to fetch contents*/
  $http.get('/pipedrive/getLeadsForMonth', function() {}).then(function successCallback(response) {

    // Loop through each lead and index them based on date
    var leads = response.data.data[0].deals;
    // Set date to first of the month
    var date = new Date(year, month, 1);
    // Define the month for the loop
    var currentMonth = date.getMonth();

    // Loop through the days in the month
    while (date.getMonth() === currentMonth) {
      // Save the date
      var currentDate = new Date(date).toISOString().replace(/T.*/, '');
      date.setDate(date.getDate() + 1);
      leadCount = 0;
      // Loop through each lead and search data for date
      for (i = 0; i < leads.length; i++) {
        if (leads[i].add_time.includes(currentDate)) {
          leadCount++
        }
      }
      leadsPerDay.push(leadCount);
    }
  }, function errorCallback(response) {
    console.log('There was a problem with your GET request.')
  });
  console.log(leadsPerDay);
  return leadsPerDay;
}

我希望这会奏效。