On Wed, Mar 5, 2014 at 1:57 PM, Heesob Park <phasis / gmail.com> wrote:

> Hi,
>
> 2014-03-05 17:31 GMT+09:00 Robert Klemme <shortcutter / googlemail.com>:
> > On Wed, Mar 5, 2014 at 8:42 AM, Heesob Park <phasis / gmail.com> wrote:
> >
> >>
> arr_even,arr_odd=arr.each_with_index.partition{|v|v[1].even?}.map{|v|v.map{|v|v[0]}}
> >
> > We can be a bit more efficient memory wise by replacing #map with
> > #each and #map!
> >
> > irb(main):008:0> arr.each_with_index.partition {|x,i| i.odd?}.each
> > {|a| a.map!(&:first)}
> > => [[11, :true, -22, [], "n"], [12, "a", 300, {}, "n-1"]]
> >
> > Here's another approach
> >
> > irb(main):014:0> arr.each_slice(2).each_with_object([[],[]])
> > {|(a,b),(even,odd)| even << a; odd << b}
> > => [[12, "a", 300, {}, "n-1"], [11, :true, -22, [], "n"]]
> >
> > irb(main):016:0> arr.each_with_index.each_with_object([[],[]])
> > {|(x,i),(even,odd)| (i.odd? ? odd : even) << x}
> > => [[12, "a", 300, {}, "n-1"], [11, :true, -22, [], "n"]]
> >
> > irb(main):023:0> arr.each_with_object([[],[]]).each_with_index {|(x,
> > (even, odd)), i| (i.odd? ? odd : even) << x}
> > => [[12, "a", 300, {}, "n-1"], [11, :true, -22, [], "n"]]
> >
> > In all cases just assign via multiple assignment:
> >
> > arr_even, arr_odd = expr...
> >
> I found a bit more compact and efficient way
>
> irb(main):037:0> arr.partition.with_index{|x,i|i.odd?}
> => [[11, :true, -22, [], "n"], [12, "a", 300, {}, "n-1"]]
>
>
Indeed Park's iteration takes the shortest time.
Partitions are way faster than .each loops.

[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
 @cstime=0.0,
 @cutime=0.0,
 @label="",
 @real=0.004411993,
 @stime=0.0,
 @total=0.0,
 @utime=0.0>