来自两个不同大小的数组的Ruby数组?

时间:2013-10-13 14:57:09

标签: ruby arrays hash map elements

我有两个daystrips的Ruby数组,以及如下所示的星期几:

days = ["Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday","Sunday"]

这里有公交车时刻表:

trips = [
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm"
]

我想要实现的结果是:

Bus-times = [
  "Monday","2.35pm","4.50pm","7.00pm",
  "Tuesday","2.35pm","4.50pm","7.00pm",
  "Wednesday","2.35pm","4.50pm","7.00pm",
  "Thusday","2.35pm","4.50pm","7.00pm",
  "Friday","2.35pm","4.50pm","7.00pm",
  "Saturday","2.35pm","4.50pm","7.00pm",
  "Sunday""2.35pm","4.50pm","7.00pm"
]

我查看了交错,zip只返回第一个结果,如果我不编写自己的函数。我还有其他选择吗?

2 个答案:

答案 0 :(得分:4)

bus_times = days.zip(trips.each_slice(3)).flatten

或者如果你想将它们保存为数组数组:

bus_times = days.zip(trips.each_slice(3)).map(&:flatten)

答案 1 :(得分:0)

这是代码:

trips.each_slice(3).flat_map.with_index(0){|a,i| a.unshift(days[i])}

,或者

[days,trips.each_slice(3).to_a ].transpose.flatten 

<强>输出

[
    "Monday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Tuesday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Wednesday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Thursday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Friday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Saturday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Sunday",
    "2.35pm",
    "4.50pm",
    "7.00pm"
]

<强>基准

require 'benchmark'

days = ["Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday","Sunday"]
trips= ["2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm"]


n = 50000
Benchmark.bm(7) do |x|
  x.report("ZIP")   { n.times{days.zip(trips.each_slice(3)).flatten} }
  x.report("MAP") { n.times{trips.each_slice(3).flat_map.with_index(0){|a,i| a.unshift(days[i])}} }
  x.report("TRANSPOSE")  { n.times{[days,trips.each_slice(3).to_a ].transpose.flatten} }
end

<强>结果

              user     system      total        real
ZIP        0.800000   0.000000   0.800000 (  0.798833)
MAP        0.600000   0.000000   0.600000 (  0.597299)
TRANSPOSE  0.820000   0.000000   0.820000 (  0.826408)