1

我有一个看起来像的方法

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

实际结构稍微复杂一点,其中要调用的方法来自不同的实例,在某些情况下,我必须通过管道传输所有参数,以免第一个参数,在其他情况下,我必须用另一个值替换第一个参数

4

2 回答 2

2

您可以使用所谓的 splat 运算符*将数组展开为参数列表:

# Call with all but the first element
m.call *args[1..-1]

# Replace first element
m.call *args[1..-1].unshift(newarg)

(一元)* 运算符在这段 Ruby 代码中做了什么?
两个数组中奇怪的乘数运算符行为散列组合

于 2013-01-15T09:04:25.137 回答
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
于 2013-01-15T10:16:42.677 回答