0

我有这个代码:

def foo( arg_array ) 
  arg_array.each do |ar|
    puts ar
  end
end 

my_array = ["Hello", "Bye", "Please"]

foo my_array # Works fine
foo "Thanks", my_array # And this not

有没有办法在不直接加入的情况下进行第二个方法调用"Thanks"

4

5 回答 5

2

Splat 数组解包:

foo ["Thanks", *my_array]
于 2012-08-12T08:23:06.980 回答
0

如果您正在寻找一种快速而干净的方式将元素添加到现有数组中,您可以使用:

foo ["Thanks"] + my_array

它创建一个包含 的单元素数组"Thanks",然后将 的内容连接my_array到它上面。如果您愿意,可以在 IRB 中查看:

my_array = ["Hello", "Bye", "Please"]
=> ["Hello", "Bye", "Please"]
["Thanks"] + my_array
=> ["Thanks", "Hello", "Bye", "Please"]
于 2012-08-11T22:51:24.450 回答
0

如果你想接受任意数量的StringorArray并将它们视为一个数组,你可以使用这个:

def foo(*arg_array)
  arg_array = arg_array.map { |arg| arg.is_a?(Array) ? arg : [arg] }.flatten(1)
  arg_array.each do |ar|
    puts ar
  end
end 

my_array = ["Hello", "Bye", "Please"]

foo my_array # print Hello Bye Please
foo "Thanks", my_array # prints Thanks Hello Bye Please
于 2012-08-11T22:58:18.233 回答
0

如果您接受更改方法,此方法将适用于数组或单个对象:

def foo(*args)
  args.each do |ar|
    puts ar
  end
end

* args将单个对象转换为数组

foo 'thanks'
# => prints 'thanks'
foo ['bar', 'baz', 'foobar']
# => prints 'bar'
# => prints 'baz'
# => prints 'foobar'

如果您不想更改方法,可以在每次调用中添加感谢数组

foo ['Thanks'] + ['to','you']
于 2012-08-12T08:57:16.353 回答
0

简单的!只需在方法定义中添加 splat 运算符 ( *)即可:arg_array

def foo( *arg_array ) 
  arg_array.each do |ar|
    puts ar
  end
end 

my_array = ["Hello", "Bye", "Please"]

foo my_array             # Works fine
foo "Thanks", my_array   # And this also
于 2012-08-12T10:05:06.757 回答