On Sat, Mar 8, 2014 at 1:16 AM, Micky <mickylmartin / gmail.com> wrote:

Indeed Park's iteration takes the shortest time.
> Partitions are way faster than .each loops.
>

If you claim that then posting only the timing of one approach won't prove
much.


> [87] pry(main)> a.size
> => 10001
> [88] pry(main)> Benchmark.measure {  a.partition.with_index{|x,i| i.odd? ?
> odd << x : even << x}  }
> => #<Benchmark::Tms:0x00000003e5a3f0
>

That does not make sense: first, you're not using #partition at all.
Without a block as criterion this just creates an Enumerator - much the
same as #each does without a block.

irb(main):017:0> a = 10.times.map {|x| "x-#{x}"}
=> ["x-0", "x-1", "x-2", "x-3", "x-4", "x-5", "x-6", "x-7", "x-8", "x-9"]
irb(main):018:0> x = a.partition
=> #<Enumerator: ["x-0", "x-1", "x-2", "x-3", "x-4", "x-5", "x-6", "x-7",
"x-8", "x-9"]:partition>
irb(main):019:0> x.class
=> Enumerator
irb(main):020:0> x.to_a
=> ["x-0", "x-1", "x-2", "x-3", "x-4", "x-5", "x-6", "x-7", "x-8", "x-9"]

Then, you're adding elements to some "odd" or "even" that you do not show
here. If you do that then you don't need partition at all. Rather use
#each_with_index and do the distribution:

irb(main):021:0> odd = []
=> []
irb(main):022:0> even = []
=> []
irb(main):023:0> a.each_with_index {|x,i| (i.odd? ? odd : even) << x}
=> ["x-0", "x-1", "x-2", "x-3", "x-4", "x-5", "x-6", "x-7", "x-8", "x-9"]
irb(main):024:0> odd
=> ["x-1", "x-3", "x-5", "x-7", "x-9"]
irb(main):025:0> even
=> ["x-0", "x-2", "x-4", "x-6", "x-8"]

If you want to use #partition in a reasonable way you need to do something
like this:

irb(main):026:0> a.each_with_index.partition {|x,i| i.odd?}.each {|x|
x.map!(&:first)}
=> [["x-1", "x-3", "x-5", "x-7", "x-9"], ["x-0", "x-2", "x-4", "x-6",
"x-8"]]

Here's another funny approach:

irb(main):030:0> odd, even = [], []
=> [[], []]
irb(main):031:0> a1, a2 = even, odd
=> [[], []]
irb(main):032:0> a.each {|x| a1 << x; a1, a2 = a2, a1}
=> ["x-0", "x-1", "x-2", "x-3", "x-4", "x-5", "x-6", "x-7", "x-8", "x-9"]
irb(main):033:0> even
=> ["x-0", "x-2", "x-4", "x-6", "x-8"]
irb(main):034:0> odd
=> ["x-1", "x-3", "x-5", "x-7", "x-9"]

Kind regards

robert

-- 
[guy, jim].each {|him| remember.him do |as, often| as.you_can - without end}
http://blog.rubybestpractices.com/