Array# method like shape in Python?

Rubies:

In the (sadly inferior) language Python, if you have an array like this…

a = [ 0, 1, 2, 3 ]

…you can change its dimensions without changing its contents (i.e.
efficiently) like this:

a.shape = [2, 2]
assert a == [ [1, 2], [3, 4] ]

What’s the equivalent in the (vastly superior) language Ruby? How does one
unflatten?

···


Phlip
http://andstuff.org/HarryPotter
– “He who has had, has been, but he who hasn’t been,
has been had” - Stanislaw Lem –

What’s the equivalent in the (vastly superior) language Ruby? How does one
unflatten?

How about ???

ruby flat.rb
[[1, 1, 1], [2, 2], [3, 3, 3, 3]]

cat flat.rb
class Array
def shape(*n)
data = self
res =
n.each do |count|
res << data.slice!(0, count)
end
res
end
end
p [1, 1, 1, 2, 2, 3, 3, 3, 3].shape(3, 2, 4)

···

On Sun, 25 May 2003 23:47:54 +0000, Phlip wrote:


Simon Strandgaard

Simon Strandgaard wrote:

How about ???

Stunning. Thanks.

But… :wink: …now I need help copying it from a KNode post running inside a
CygWin XFree86 fvwm2 X server, into WinXP’s clipboard so I can then paste
it into Scite. No lie.

Don’t worry. I’l figure this one out…

···


Phlip
greencheese.org
– Have a :slight_smile: day –

Hi –

What’s the equivalent in the (vastly superior) language Ruby? How does one
unflatten?

How about ???

ruby flat.rb
[[1, 1, 1], [2, 2], [3, 3, 3, 3]]

cat flat.rb
class Array
def shape(*n)
data = self
res =
n.each do |count|
res << data.slice!(0, count)
end
res
end
end
p [1, 1, 1, 2, 2, 3, 3, 3, 3].shape(3, 2, 4)

That modifies the original array, though, which probably isn’t what’s
wanted.

Less impact-ful way:

class Array
def shape(*n)
i = 0
n.map {|e| s=i; i+=e; slice(s,e)}
end
end

David

···

On Mon, 26 May 2003, Simon Strandgaard wrote:

On Sun, 25 May 2003 23:47:54 +0000, Phlip wrote:


David Alan Black
home: dblack@superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav