我的方法看起来像
def SomeMethod (*args)
m = if args.length > 0 then
self.method(:method1)
else
self.method(:method2)
end
m.call ... #need to either pipe all arguments aside from the first
#and in other cases substitute the first argument
end
实际结构更复杂,要调用的方法来自不同的实例,在某些情况下,我必须管道所有参数,以免第一个,在其他情况下,我必须用第一个参数替换第一个参数另一个值
答案 0 :(得分:2)
您可以使用所谓的splat运算符*
将数组扩展为参数列表:
# Call with all but the first element
m.call *args[1..-1]
# Replace first element
m.call *args[1..-1].unshift(newarg)
What does the (unary) * operator do in this Ruby code?
Weird multiplicator operator behavior in a two arrays to hash combination
答案 1 :(得分:0)
您可以尝试使用哈希
def SomeMethod (hash_arg={})
m = unless hash_arg.blank? then
self.method(:method1)
else
self.method(:method2)
end
m.call ... #need to either pipe all arguments aside from the first
#and in other cases substitute the first argument
#Check if a certain arg has been passed=> do_something unless hash_arg[:certain_arg].nil?
end