1

days以下に示すように、とtrips、および曜日の2 つの 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、独自の関数を記述しない場合にのみ最初の結果を返します。他にどのようなオプションがありますか?

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 に答える