我试图将方法的第一个参数设置为可选,然后是任意数量的args。例如:
def dothis(value=0, *args)
我遇到的问题是,这似乎不太可能吗?当我打电话给dothis("hey", "how are you", "good")
时,我希望它会将值设置为默认值为0,但它只是制作value="hey"
。有没有办法完成这种行为?
答案 0 :(得分:5)
这不可能直接在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引入了命名哈希参数,它为你处理了很多选项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"]
答案 1 :(得分:3)
这篇文章有点陈旧,但如果有人正在寻找最佳解决方案,我想做出贡献。 从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")
答案 2 :(得分:1)
您需要使用命名参数来完成此任务:
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}
答案 3 :(得分:0)
通过使用value = 0,您实际上将0赋值给值。只是为了保留这个值,您可以使用上面提到的解决方案,也可以在每次调用此方法时使用值def dothis(value,digit = [* args])。
未提供参数时使用默认参数。
我遇到了类似的问题,我通过使用:
来克服它def check(value=0, digit= [*args])
puts "#{value}" + "#{digit}"
end
并简单地调用这样的支票:
dothis(value, [1,2,3,4])
您的值将是默认值,其他值属于其他参数。