给定一组参数,如何将这些参数发送到 Ruby 中的特定函数? [英] Given an array of arguments, how do I send those arguments to a particular function in Ruby?
问题描述
原谅初学者的问题,但说我有一个数组:
Forgive the beginner question, but say I have an array:
a = [1,2,3]
还有一个函数;假设它是一个实例函数:
And a function somewhere; let's say it's an instance function:
class Ilike
def turtles(*args)
puts args.inspect
end
end
如何使用 a
调用 Ilike.turtles
,就像调用 (Ilike.new).turtles(1,2,3)
代码>.
How do I invoke Ilike.turtles
with a
as if I were calling (Ilike.new).turtles(1,2,3)
.
我熟悉 send
,但这似乎并没有将数组转换为参数列表.
I'm familiar with send
, but this doesn't seem to translate an array into an argument list.
与我正在寻找的并行的是 Javascript apply
,它等效于 call
但将数组转换为参数列表.
A parallel of what I'm looking for is the Javascript apply
, which is equivalent to call
but converts the array into an argument list.
推荐答案
如您所知,在定义方法时,可以使用 *
将参数列表转换为数组.同样,当您调用方法时,您可以使用 *
将数组转换为参数列表.所以在你的例子中你可以这样做:
As you know, when you define a method, you can use the *
to turn a list of arguments into an array. Similarly when you call a method you can use the *
to turn an array into a list of arguments. So in your example you can just do:
Ilike.new.turtles(*a)
这篇关于给定一组参数,如何将这些参数发送到 Ruby 中的特定函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!