我想设置方法的第一个参数是可选的,后面跟着任意数量的参数。例如:Ruby可选参数和多个参数
def dothis(value=0, *args)
我遇到的问题是,它似乎并没有实际上可能?当我打电话给dothis("hey", "how are you", "good")
时,我希望它将默认值设置为0,但它只是使value="hey"
。有什么办法来完成这种行为?
我想设置方法的第一个参数是可选的,后面跟着任意数量的参数。例如:Ruby可选参数和多个参数
def dothis(value=0, *args)
我遇到的问题是,它似乎并没有实际上可能?当我打电话给dothis("hey", "how are you", "good")
时,我希望它将默认值设置为0,但它只是使value="hey"
。有什么办法来完成这种行为?
这直接是不可能的在Ruby中
,有很多的选择,虽然这取决于你与你的扩展PARAMS做什么,以及该方法打算做什么。
显而易见的选择使用哈希语法
def dothis params
value = params[:value] || 0
list_of_stuff = params[:list] || []
Ruby有解决这个漂亮的调用约定,你不需要提供哈希括号{}
dothis :list => ["hey", "how are you", "good"]
是
1)取名叫PARAMS
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)红宝石2.0引入命名散列参数,其中处理了很多选项1,上面为你:
def dothis value: 0, list: []
# Local variables value and list already defined
# and defaulted if necessary
调用相同的方式(1):通过使用值= 0
dothis :list => ["hey", "how are you", "good"]
感谢您的帮助。 @凯尔,我也喜欢你的解决方案,但我不确定我想大量地命名参数,因为在某些情况下,会有很多参数。不过,我一定会尝试两种方式,看看我更喜欢哪一种。感谢大家! – 2013-02-28 15:37:51
@ adback03没问题,我更喜欢Neils的解决方案;) – Kyle 2013-02-28 15:41:56
您需要使用命名参数来实现:
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}
你实际上是到值分配0。为了保留这个值,你可以使用上面提到的解决方案,或者每次调用def dothis(value,digit = [* args])这个方法时简单地使用value。
未提供参数时使用默认参数。
我遇到了类似的问题,我挺过来了,通过使用:
def check(value=0, digit= [*args])
puts "#{value}" + "#{digit}"
end
,并简单地调用检查这样的:
dothis(value, [1,2,3,4])
你的价值将是默认和其他值属于其他论据。
这篇文章有点旧了,但是如果有人正在寻找最佳解决方案,我想贡献一下。 由于红宝石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"])
您也可以用贪婪的关键字做同样的事情** 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")
为downvote原因...? – 2013-02-28 15:20:27
你传递了第一个参数“hey”,它被赋值为'value'。因此默认值不起作用。它有什么问题? – sawa 2013-02-28 15:23:15
我试图实现的是保留值= 0并能够认识到“嘿”是参数的开始,而不是价值。这是因为我正在调用一个函数,其中值为0的时间约为90%。但每过一段时间,它都需要成为一个。这就是为什么我希望将它用作默认参数。 – 2013-02-28 15:26:26