nested arrays

M

Mathias

Hi,

I'm new to this gem called ruby, but having difficulties generating nested
arrays. Why is: var = Array.new(p, Array.new(q, 0)) not the same as:
var = Array.new(p) {Array.new(q, 0)} ?? (I know the later one works, but it
took me ages for figuring this out :D)

Thnx for your answer.. Mathias
 
R

Robert Klemme

Mathias said:
Hi,

I'm new to this gem called ruby, but having difficulties generating
nested arrays. Why is: var = Array.new(p, Array.new(q, 0)) not the
same as:
var = Array.new(p) {Array.new(q, 0)} ?? (I know the later one works,
but it took me ages for figuring this out :D)

Thnx for your answer.. Mathias

Because in the first case you provide just a single object that is used for
initialization while the second case you provide a code block that is
executed once for each array element to initialize. Does that help?

Kind regards

robert
 
M

Mathias

Hi Robert,
Because in the first case you provide just a single object that is used
for initialization while the second case you provide a code block that is
executed once for each array element to initialize. Does that help?

Yepp, and "language reference" says:
Array.new(size, obj) means [... is created with size copies of obj (that is,
size references to the same obj)..] I possible read the _same_ over and
over again ;).


thanks for fast reply, Mathias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top