将数组元素返回到参数中的可变长度数组

时间:2022-06-01 19:53:52

I have a ruby function with the following function header def get_value( default, *args ), and I'm using recursion in my function body, and I want to pass the args array without the first element, what I have used is get_value(default, args.slice(1, args.length)), however, after using a debugger, I found that the args in the recursed function was an array of arrays, and the inner arrays contained my elements. So if my main array was [:files, :mode] the recursed array would be [[:mode]]. How can I make it that is becomes [:mode]?

我有一个ruby函数,带有以下函数头def get_value(默认,* args),我在函数体中使用递归,我想传递没有第一个元素的args数组,我使用的是get_value(但是,在使用调试器后,我发现递归函数中的args是一个数组数组,而内部数组包含我的元素。默认情况下,args.slice(1,args.length))。因此,如果我的主数组是[:files,:mode],则递归数组将为[[:mode]]。我怎样才能成为[:mode]?

1 个解决方案

#1


3  

Call get_value with the splat operator:

使用splat运算符调用get_value:

get_value(default, *args.slice(1, args.length))

or with additional brevity

或者更简洁

get_value(default, *args[1..-1])

#1


3  

Call get_value with the splat operator:

使用splat运算符调用get_value:

get_value(default, *args.slice(1, args.length))

or with additional brevity

或者更简洁

get_value(default, *args[1..-1])