从给定数组创建数组

时间:2013-11-18 14:24:14

标签: arrays ruby-on-rails-3

是否可以从另一个阵列创建数组?
Lang:Ruby on Rails

案例

工人有权填写自己的工作时间。有时他们会忘记这样做。这就是我想要解决的问题。最后,我想要一个带有时间码的数组,工作人员忘记记录他的工作时间。

timecodes = [201201, 201202, 201203, 201204, 201205, 201206, 201207, 201208, 201209, 201210, 201211, 201212, 201213, 201301, 201302, 201304, 201305, 201306, ...]

工人从201203年到20120年与我们合作。

timecards = [201203, 201204, 201205, 201207, 201208, 201209]

如您所见,他忘了注册201206。

我想做什么

# Create Array from timecode on start to timecode on end
worked_with_us = [201203, 201204, 201205, 201206, 201207, 201208, 201209]  
   #=> This is the actual problem, how can I automate this?

forgot_to_register = worked_with_us.?????(timecards)
forgot_to_register = worked_with_us - timecards  # Thanks Zwippie
   #=> [201206]

现在我知道工人忘了记录他的工作时间。

一起

  1. 如何从另一个数组创建一个数组,给出一个起始值和结束值?

1 个答案:

答案 0 :(得分:2)

您可以使用-(减号)减去数组:

[1, 2, 3] - [1, 3] = [2]

要构建一个包含年/月的数组,可以使用Range来完成,但这只适用于每年构建一个数组,例如:

months = (2012..2013).map do |year|
  ("#{year}01".."#{year}12").to_a.collect(&:to_i)
end.flatten

  => [201201, 201202, 201203, 201204, 201205, 201206, 201207, 201208, 201209, 201210, 201211, 201212, 201301, 201302, 201303, 201304, 201305, 201306, 201307, 201308, 201309, 201310, 201311, 201312]

对于动态创建这些范围的功能:

def month_array(year_from, year_to, month_from=1, month_to=12)
  (year_from..year_to).map do |year|
    # Correct from/to months
    mf = year_from == year ? month_from : 1
    mt = year_to == year ? month_to : 12

    (mf..mt).map do |month|
      ("%d%02d" % [year, month]).to_i
    end
  end.flatten
end

更新:你想要这个方法的其他输入参数,但我希望你能自己解决这个问题。 :)

相关问题