Search code examples
ruby-on-railsrubybit-shiftsplat

Ruby splat and << operators


I want to do this:

a << *b

but this happens in irb:

1.9.3p327 :020 > a
 => [1, 2, 3, 4] 
1.9.3p327 :021 > b
 => [5, 6, 7] 
1.9.3p327 :022 > a << *b
SyntaxError: (irb):22: syntax error, unexpected tSTAR
a << *b
      ^

Am I missing something?


Solution

  • Look the reason here :

     a = [1, 2, 3, 4] 
     b = [5, 6, 7] 
     p a.<<(*b)
     # ~> -:3:in `<<': wrong number of arguments (3 for 1) (ArgumentError)
     # ~>  from -:3:in `<main>'
    

    << method expects only one argument.So now as below splat(*) is an operator,which will create 5,6,7 ,which << method do not expect,rather it expects only one object. Thus design of Ruby don't allowing * before b.

     a = [1, 2, 3, 4] 
     b = [5, 6, 7] 
     p a << *
     # ~> -:3: syntax error, unexpected *
    
     a = [1, 2, 3, 4] 
     b = [5, 6, 7] 
     p a << *b
     # ~> -:3: syntax error, unexpected *
     # ~> p a << *b
     # ~>         ^
    

    That is why the 2 legitimate errors :

    • wrong number of arguments (3 for 1) (ArgumentError)

    • syntax error, unexpected *

    Probably you can use -

     a = [1, 2, 3, 4] 
     b = [5, 6, 7] 
     p a.push(*b)
     # >> [1, 2, 3, 4, 5, 6, 7]