Ruby可选参数和多个参数

我试图将方法的第一个参数设置为可选,然后是任意数量的args。 例如:

def dothis(value=0, *args) 

我遇到的问题是,这似乎不太可能吗? 当我打电话给dothis("hey", "how are you", "good")我希望它将值设置为默认为0,但它只是使value="hey" 。 有没有办法完成这种行为?

这在Ruby中是不可能的

但是有很多选择,取决于你对扩展参数的处理方式,以及方法的用途。

明显的选择是

1)使用哈希语法获取命名参数

 def dothis params value = params[:value] || 0 list_of_stuff = params[:list] || [] 

Ruby有很好的调用约定,你不需要提供hash {}括号

 dothis :list => ["hey", "how are you", "good"] 

2)将值移到最后,并为第一个参数取一个数组

 def dothis list_of_stuff, value=0 

这样称呼:

 dothis ["hey", "how are you", "good"], 17 

3)使用代码块提供列表

 dothis value = 0 list_of_stuff = yield 

像这样打电话

 dothis { ["hey", "how are you", "good"] } 

4)Ruby 2.0引入了名为hash的参数,它可以为你处理上面的很多选项1:

 def dothis value: 0, list: [] # Local variables value and list already defined # and defaulted if necessary 

调用与(1)相同的方式:

 dothis :list => ["hey", "how are you", "good"] 

这篇文章有点旧,但如果有人正在寻找最佳解决方案,我想做出贡献。 从ruby 2.0开始 ,您可以使用哈希定义的命名参数轻松完成。 语法简单易读。

 def do_this(value:0, args:[]) puts "The default value is still #{value}" puts "-----------Other arguments are ---------------------" for i in args puts i end end do_this(args:[ "hey", "how are you", "good"]) 

您也可以使用greedy关键字** args作为哈希来执行相同的操作,如下所示:

 #**args is a greedy keyword def do_that(value: 0, **args) puts "The default value is still #{value}" puts '-----------Other arguments are ---------------------' args.each_value do |arg| puts arg end end do_that(arg1: "hey", arg2: "how are you", arg3: "good") 

您需要使用命名参数来完成此任务:

 def dothis(args) args = {:value => 0}.merge args end dothis(:value => 1, :name => :foo, :age => 23) # => {:value=>1, :name=>:foo, :age=>23} dothis(:name => :foo, :age => 23) # => {:value=>0, :name=>:foo, :age=>23} 

通过使用value = 0,您实际上为值赋值0。 只是为了保留这个值,您可以使用上面提到的解决方案,也可以只在每次调用此方法时使用值def dothis(value,digit = [* args])。

未提供参数时使用默认参数。

我遇到了类似的问题,我通过使用:

 def check(value=0, digit= [*args]) puts "#{value}" + "#{digit}" end 

并简单地调用这样的检查:

 dothis(value, [1,2,3,4]) 

您的值将是默认值,其他值属于其他参数。