Syntax error with array interpolation

Discussion in 'Ruby' started by Ronald Fischer, Jun 25, 2007.

  1. Below is a code snippet which gives me some headache:

    def headache
    yield(*(foo(1)),"bar")
    end

    def foo(n)
    [n,n+2,n+5]
    end

    headache { |a,b,c,d| puts a.to_s; puts b.to_s; puts c.to_s; puts d }

    I had expected that this would print

    1
    3
    6
    bar


    But Ruby 1.8.5 complains:

    /headache.rb: line 1: def: command not found
    /headache.rb: line 2: syntax error near unexpected token `*'
    '/headache.rb: line 2: ` yield(*(foo(1)),"bar")

    and Ruby 1.8.6 complains:

    H:/tmp/headache.rb:2: syntax error, unexpected tSTRING_BEG, expecting
    tAMPER
    yield(*(foo(1)),"bar") ^
    H:/tmp/headache.rb:2: syntax error, unexpected ')', expecting kEND
    H:/tmp/headache.rb:10: syntax error, unexpected $end, expecting kEND


    There must something be wrong with the way I'm doing array
    interpolation,
    but I can't spot the error....

    Ronald
    --=20
    Ronald Fischer <>
    Phone: +49-89-452133-162
    =20
    Ronald Fischer, Jun 25, 2007
    #1
    1. Advertising

  2. Ronald Fischer wrote:
    > Below is a code snippet which gives me some headache:
    >
    > def headache
    > yield(*(foo(1)),"bar")
    > end


    You can't use a 'splatted' array anywhere in a method call except at the
    end:

    def foo(a, b, c)
    p [a, b, c]
    end

    foo(1, 2, *[3]) #=> works
    foo(1, *[3], "asdf") #=> doesn't work

    I'm not quite sure why this should be, since it has an unambiguous
    meaning, unlike defining a method with a splat in the middle of the
    arguments:

    def bar(a, *b, c=0)
    ...
    end

    The splat operator is a bit mysterious to me in this regard.....

    best,
    Dan

    --
    Posted via http://www.ruby-forum.com/.
    Daniel Lucraft, Jun 25, 2007
    #2
    1. Advertising

  3. Daniel Lucraft wrote:
    >
    > You can't use a 'splatted' array anywhere in a method call except at the
    > end:
    >


    Pardon me: and before a block argument:
    foo(1, 2, *[3], &block)

    Dan

    --
    Posted via http://www.ruby-forum.com/.
    Daniel Lucraft, Jun 25, 2007
    #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. Balaji
    Replies:
    3
    Views:
    10,073
  2. Ronald Fischer

    Syntax error with array interpolation

    Ronald Fischer, Jun 25, 2007, in forum: Ruby
    Replies:
    0
    Views:
    77
    Ronald Fischer
    Jun 25, 2007
  3. Good Night Moon
    Replies:
    9
    Views:
    263
    Rick DeNatale
    Jul 25, 2007
  4. Mark Richards
    Replies:
    3
    Views:
    299
    Tad McClellan
    Nov 18, 2007
  5. Isaac Won
    Replies:
    15
    Views:
    220
    Oscar Benjamin
    Jan 24, 2013
Loading...

Share This Page