2011-02-11 54 views
25

我有一个方法,它应该接受最多2个参数。它的代码是这样的:具有最大参数数量的Ruby方法

def method (*args) 
    if args.length < 3 then 
    puts args.collect 
    else 
    puts "Enter correct number of arguments" 
    end 
end 

有更好的方法来指定它吗?

回答

67

根据您希望该方法冗长而严格的方法,您有多种选择。

# force max 2 args 
def foo(*args) 
    raise ArgumentError, "Too many arguments" if args.length > 2 
end 

# silently ignore other args 
def foo(*args) 
    one, two = *args 
    # use local vars one and two 
end 

# let the interpreter do its job 
def foo(one, two) 
end 

# let the interpreter do its job 
# with defaults 
def foo(one, two = "default") 
end 
+24

+1但你忘了`def(one,two,* ignored); end` – 2011-02-11 13:25:04

12

如果最大值是两个参数,为什么使用这样的splat运算符呢?只要明确。 (除非你有没有告诉我们其他的一些约束。)

def foo(arg1, arg2) 
    # ... 
end 

或者......

def foo(arg1, arg2=some_default) 
    # ... 
end 

甚至......

def foo(arg1=some_default, arg2=some_other_default) 
    # ... 
end 
5

引发错误更好。如果论点不正确,这是严重的问题,不应该通过你的谦卑puts

def method (*args) 
    raise ArgumentError.new("Enter correct number of arguments") unless args.length < 3 
    puts args.collect 
end 
相关问题