1

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?

4

5 回答 5

5

我已经评论了它,现在添加它来回答;-)

a += b 会做你的工作

于 2013-07-07T13:23:51.487 回答
4

尝试这个:

 a.concat(b)

它将输出:

=> [1, 2, 3, 4, 5, 6, 7] 
于 2013-07-07T09:54:37.377 回答
3

看看这里的原因:

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

<<方法只需要一个参数。所以现在如下所示 splat( *) 是一个运算符,它将创建,不期望5,6,7哪个方法,而是只需要一个对象。因此 Ruby 的设计之前<<不允许。*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
 # ~>         ^

这就是为什么 2 个合法错误:

  • 参数数量错误(1 为 3)(ArgumentError)

  • 语法错误,意外 *

也许你可以使用 -

 a = [1, 2, 3, 4] 
 b = [5, 6, 7] 
 p a.push(*b)
 # >> [1, 2, 3, 4, 5, 6, 7]
于 2013-07-07T09:52:21.120 回答
1

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]
于 2013-07-08T05:13:52.827 回答
1

检查类型签名:ary << obj → ary。它只需要一个参数。尝试:a.push(*b) (push(obj, ... ) → ary)

于 2013-07-07T09:52:22.333 回答