1

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

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如果我不编写自己的函数,则只返回第一个结果。我还有什么其他选择?

4

2 回答 2

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

或者如果您想将它们保留为数组数组:

bus_times = days.zip(trips.each_slice(3)).map(&:flatten)
于 2013-10-13T15:04:15.493 回答
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)
于 2013-10-13T15:04:43.607 回答