是否可以在Ruby中的方法调用中解包数组?

时间:2012-08-11 22:44:37

标签: ruby arrays

我有这段代码:

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"

5 个答案:

答案 0 :(得分:1)

Splat array unpack:

foo ["Thanks", *my_array]

答案 1 :(得分:0)

如果您正在寻找一种快速而简洁的方法将元素添加到现有阵列中,您可以使用:

foo ["Thanks"] + my_array

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

my_array = ["Hello", "Bye", "Please"]
=> ["Hello", "Bye", "Please"]
["Thanks"] + my_array
=> ["Thanks", "Hello", "Bye", "Please"]

答案 2 :(得分:0)

如果您想接受任意数量的StringArray并将其视为单个数组,则可以使用此选项:

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

答案 3 :(得分: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']

答案 4 :(得分: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