Reputation: 2209
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?
Upvotes: 1
Views: 374
Reputation: 135227
Given
a = [1, 2, 3, 4]
b = [5, 6, 7]
The solution you want is
a.concat b
# => [1, 2, 3, 4, 5, 6, 7]
However, you might find this a little interesting
b.each &a.method(:<<)
a
# => [1, 2, 3, 4, 5, 6, 7]
This says "call method a#<<
on each element in b"
Equivalent to
b.each &a.method(:push)
a
# => [1, 2, 3, 4, 5, 6, 7]
Upvotes: 2
Reputation: 118271
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]
Upvotes: 3
Reputation: 791
Check the type signature: ary << obj → ary. It expects exactly one parameter. Try: a.push(*b) (push(obj, ... ) → ary)
Upvotes: 0