我正在尝试将方法的第一个参数设置为可选参数,然后是任意数量的参数。例如:
def dothis(value=0, *args)
我遇到的问题是似乎这是不可能的?当我调用dothis("hey", "how are you", "good")
时,我希望它将值设置为默认值0,但实际上它只是使value="hey"
。有没有办法实现这种行为?
我正在尝试将方法的第一个参数设置为可选参数,然后是任意数量的参数。例如:
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] || []
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引入了命名哈希参数,可以为您处理上述选项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"]
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 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分配给value。为了保留值,您可以使用上述提到的解决方案或每次调用此方法时简单地使用value def dothis(value,digit = [* args])。
默认参数在未提供参数时使用。
我遇到了类似的问题,并通过使用以下方式解决:
def check(value=0, digit= [*args])
puts "#{value}" + "#{digit}"
end
而且只需像这样调用check:
dothis(value, [1,2,3,4])
你的值将会是默认值,其他的值属于其他参数。
"hey"
,它被分配给了value
。因此默认值无效。有什么问题吗? - sawa