我有一个接受splat操作符的方法:
def hello(foo,*bar) #... do some stuff end
我有一个可变长度的数组,我想发送到这个hello方法:
arr1 = ['baz','stuff'] arr2 = ['ding','dong','dang']
我想使用arr1和arr2作为该方法的参数调用该方法,但是我不断被挂起,因为* bar被解释为一个数组而不是单独的参数.为了使事情更加有趣,我根本无法更改你好的方法.
我正在寻找类似于this SO question但在ruby的东西.
解决方法
尝试这样调用它
hello(arr1,*arr2)
这是一个穿过irb
irb(main):002:0> def hello(foo,*bar) irb(main):003:1> puts foo.inspect irb(main):004:1> puts bar.inspect irb(main):005:1> end => nil irb(main):006:0> arr1 = ['baz','stuff'] => ["baz","stuff"] irb(main):007:0> arr2 = ['ding','dang'] => ["ding","dong","dang"] irb(main):008:0> hello(arr1,arr2) ["baz","stuff"] [["ding","dang"]] => nil irb(main):009:0> hello(arr1,*arr2) ["baz","stuff"] ["ding","dang"] => nil
通过将*添加到第二个数组,它将它们视为一个数组,而不是一个数组的数组,这是你想要的,我认为