Ruby中具有默认值的可选参数 [英] Optional arguments with default value in Ruby

查看:251
本文介绍了Ruby中具有默认值的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个具有默认值的可选参数的函数

I would like to create a function that has optional arguments with default values

def my_function(a = nil, b=nil, c=500)

end

并使用我仅想指定的参数调用函数

and call the function with the arguments I would like to specify only

my_function(b=100)

如何在Ruby 1.9.2中完成此操作?

How do I accomplish this in Ruby 1.9.2?

推荐答案

在Ruby中,您不能做到这一点(或类似的目的)< 2.0.您能做的最好的事情是:

You cannot do that (or something similar) in Ruby < 2.0. The best you could do is:

def my_function(h = {})
  h[:c] ||= 500
  # Use h[:a], h[:b], h[:c]
  ...
end

my_function(b: 100)

这篇关于Ruby中具有默认值的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆