# Nested arrays

**URL:** <https://www.ruby-forum.com/t/nested-arrays/71970>\
**Category:** Ruby\
**Created:** [February 22, 2006, 6:56pm UTC](https://www.ruby-forum.com/t/nested-arrays/71970 "2006-02-22T18:56:21Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mathias](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/bbe5ce/32.png) [@Mathias](https://www.ruby-forum.com/u/Mathias)\
**Post date:** [February 22, 2006, 6:56pm UTC](https://www.ruby-forum.com/t/nested-arrays/71970/1 "2006-02-22T18:56:21Z")

</div>

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§ {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

---

<div class="post-metadata">

**Author:** ![Mathias](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/bbe5ce/32.png) [@Mathias](https://www.ruby-forum.com/u/Mathias)\
**Post date:** [February 22, 2006, 6:59pm UTC](https://www.ruby-forum.com/t/nested-arrays/71970/2 "2006-02-22T18:59:27Z")

</div>

Mathias [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 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

```

---

<div class="post-metadata">

**Author:** ![Mathias](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/bbe5ce/32.png) [@Mathias](https://www.ruby-forum.com/u/Mathias)\
**Post date:** [February 22, 2006, 7:45pm UTC](https://www.ruby-forum.com/t/nested-arrays/71970/3 "2006-02-22T19:45:03Z")

</div>

Hi Robert,

> > nested arrays. Why is: var = Array.new(p, Array.new(q, 0)) not the  
> > same as:  
> > var = Array.new§ {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?

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
