insert an array into an array

Discussion in 'Ruby' started by jtprince, Jul 30, 2011.

  1. jtprince

    jtprince Guest

    I need to be able to insert a single element array into another array. Easy, right?

    >> ar = %w(one two three)

    => ["one", "two", "three"]

    # insertion of elements into an array is easy :)

    >> ar[1,0] = 'chicken'

    => "chicken"
    >> ar

    => ["one", "chicken", "two", "three"]

    # now, let's insert an array into the array:
    >> ar[1,0] = ['pancake']

    => ["pancake"]
    >> ar

    => ["one", "pancake", "chicken", "two", "three"]
    # ??????

    What I need is this after an insertion:
    ["one", ["pancake"], "chicken", "two", "three"]

    many thanks!
    jtprince, Jul 30, 2011
    #1
    1. Advertising

  2. On 30.07.2011 02:18, jtprince wrote:
    > I need to be able to insert a single element array into another array. Easy, right?
    >
    >>> ar = %w(one two three)

    > => ["one", "two", "three"]
    >
    > # insertion of elements into an array is easy :)
    >
    >>> ar[1,0] = 'chicken'

    > => "chicken"
    >>> ar

    > => ["one", "chicken", "two", "three"]
    >
    > # now, let's insert an array into the array:
    >>> ar[1,0] = ['pancake']

    > => ["pancake"]
    >>> ar

    > => ["one", "pancake", "chicken", "two", "three"]
    > # ??????
    >
    > What I need is this after an insertion:
    > ["one", ["pancake"], "chicken", "two", "three"]
    >
    > many thanks!


    irb(main):001:0> a=%w{a b c}
    => ["a", "b", "c"]
    irb(main):002:0> a[1,0]=[['x']]
    => [["x"]]
    irb(main):003:0> a
    => ["a", ["x"], "b", "c"]

    Kind regards

    robert

    --
    remember.guy do |as, often| as.you_can - without end
    http://blog.rubybestpractices.com/
    Robert Klemme, Jul 30, 2011
    #2
    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. =?Utf-8?B?UmFlZCBTYXdhbGhh?=

    Insert Byte Element into array of bytes

    =?Utf-8?B?UmFlZCBTYXdhbGhh?=, Mar 28, 2005, in forum: ASP .Net
    Replies:
    0
    Views:
    483
    =?Utf-8?B?UmFlZCBTYXdhbGhh?=
    Mar 28, 2005
  2. Harry Zoroc
    Replies:
    1
    Views:
    921
    Gregory Vaughan
    Jul 12, 2004
  3. impulse()
    Replies:
    0
    Views:
    2,531
    impulse()
    Oct 13, 2006
  4. Replies:
    5
    Views:
    248
  5. Sergio del Amo
    Replies:
    4
    Views:
    228
Loading...

Share This Page