Returns a new array, optionally with a size and initial value (that
is, anInteger references to the same anObject).
Array.new #=> []
Array.new(2) #=> [nil, nil]
Array.new(5, "A") #=> ["A", "A", "A", "A", "A"]
Array.new(2, Hash.new) #=> [{}, {}]
“Who is General Failure and why is he reading my hard disk?”
Microsoft spel chekar vor sail, worgs grate !!
– Felix von Leitner, leitner@inf.fu-berlin.de
Yeah. I always wished there was a nice way to do that, like with blocks.
For example:
a=Array.new(2) { }
[, ]
a[0].push(1)
[1]
a
[[1], ]
So Array.new yields the block twice, the return values of which are the
elements in the array. I guess we could pass in the index into the block,
too, if we wanted. Setting up a triangular matrix (something I know each of
you wants to do on a daily basis) would be as cute as this:
Array.new(n) {|i| Array.new(n-i)}
Anyway, it feels like a Ruby thing to me. Don’t you think so? I don’t know
how I would extend this myself, though. (My Ruby isn’t that fancy yet.)
Chris
···
----- Original Message -----
From: “gminick” gminick@underground.org.pl
Newsgroups: comp.lang.ruby
Sent: Sunday, November 24, 2002 2:42 PM
Subject: Not supposed behaviour of Array.new(2,)
Hi,
a=[,]
[, ]
a[0].push(1)
[1]
a
[[1], ]
Works great, isn’t it ?
Now, let’s do “the same” with Array.new method:
a=Array.new(2,)
[, ]
a[0].push(1)
[1]
a
[[1], [1]]
It isn’t strange for me (I know that kind of behaviour from python),
but, is it documented anywhere ? I’m just searching for a point of
reference… ;]
–
gminick (at) underground.org.pl http://gminick.linuxsecurity.pl/
[ “Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej.” ]
Yeah. I always wished there was a nice way to do that, like with
blocks.
I think in 1.7.2 and later you can do just exactly like that. A
wish come true?
I think it is similar to the difference between text books and journal
papers. Text books give you solid fundamental understanding, but they do
not cover the latest technologies. In Ruby, probably this discussion
group is one of the representatives of the Ruby “journal papers”. I also
knew that particular array feature from following this discussion group
and not from other references. On the other hand, if you know everything
in the pickaxe book, I think you are already a very solid rubyist.