nested arrays

Discussion in 'Ruby' started by Mathias, Feb 22, 2006.

  1. Mathias

    Mathias Guest

    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
    Mathias, Feb 22, 2006
    #1
    1. Advertising

  2. Mathias <> 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
    Robert Klemme, Feb 22, 2006
    #2
    1. Advertising

  3. Mathias

    Mathias Guest

    Hi Robert,

    >> 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?


    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
    Mathias, Feb 22, 2006
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Russ Perry Jr
    Replies:
    2
    Views:
    4,134
    Russ Perry Jr
    Aug 20, 2004
  2. Chad E. Dollins
    Replies:
    3
    Views:
    655
    Kai-Uwe Bux
    Nov 8, 2005
  3. request@no_spam.com
    Replies:
    5
    Views:
    424
  4. Ultrus
    Replies:
    3
    Views:
    378
    Stefan Behnel
    Jul 9, 2007
  5. Philipp
    Replies:
    21
    Views:
    1,127
    Philipp
    Jan 20, 2009
Loading...

Share This Page