[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: group array elements in groups of two

Yukihiro Matsumoto

9/17/2007 3:35:00 PM

Hi,

In message "Re: group array elements in groups of two"
on Tue, 18 Sep 2007 00:18:09 +0900, Emmanuel Oga <oga_emmanuel_oga@yahoo.com.ar> writes:

|A better way to do this? :
|
|arr= [1, 2, 3, 4, 5, 6, 7, 8]
|new= []
|while !arr.empty?
| elem1, elem2= arr.pop, arr.pop
| new << [elem2, elem1];
|end
|new.reverse!
|
|new= [[1, 2], [3, 4], [5, 6], [7, 8]]

require 'enumerator'
arr= [1, 2, 3, 4, 5, 6, 7, 8]
new=arr.to_enum(:each_slice, 2).to_a

3 Answers

William James

9/17/2007 4:07:00 PM

0

On Sep 17, 10:35 am, Yukihiro Matsumoto <m...@ruby-lang.org> wrote:
> Hi,
>
> In message "Re: group array elements in groups of two"
> on Tue, 18 Sep 2007 00:18:09 +0900, Emmanuel Oga <oga_emmanuel_...@yahoo.com.ar> writes:
>
> |A better way to do this? :
> |
> |arr= [1, 2, 3, 4, 5, 6, 7, 8]
> |new= []
> |while !arr.empty?
> | elem1, elem2= arr.pop, arr.pop
> | new << [elem2, elem1];
> |end
> |new.reverse!
> |
> |new= [[1, 2], [3, 4], [5, 6], [7, 8]]
>
> require 'enumerator'
> arr= [1, 2, 3, 4, 5, 6, 7, 8]
> new=arr.to_enum(:each_slice, 2).to_a

Nirvana at last! I won a round of golf with
Matz!

YM: .to_enum(:each_slice, 2).to_a
WJ: .enum_slice(2).to_a

Phrogz

9/17/2007 4:13:00 PM

0

On Sep 17, 10:07 am, William James <w_a_x_...@yahoo.com> wrote:
> Nirvana at last! I won a round of golf with
> Matz!
>
> YM: .to_enum(:each_slice, 2).to_a
> WJ: .enum_slice(2).to_a

Perhaps, but you both sliced your shots.

Simon Kröger

9/17/2007 8:05:00 PM

0

William James wrote:
> [...]
> Nirvana at last! I won a round of golf with
> Matz!
>
> YM: new=arr.to_enum(:each_slice, 2).to_a
> WJ: new=arr.enum_slice(2).to_a
SK: new=*arr.enum_slice(2)

cheers

Simon