Ruby 可选参数和多个参数 [英] Ruby Optional Parameters and Multiple Parameters
问题描述
我试图将方法的第一个参数设置为可选参数,然后是任意数量的参数.例如:
I am trying to set the first argument to a method as being optional, followed by any number of args. For example:
def dothis(value=0, *args)
我遇到的问题是这似乎实际上不可能?当我调用 dothis("hey", "how are you", "good")
时,我希望它会将 value 设置为默认为 0,但它只是使 value="嘿"
.有什么办法可以实现这种行为吗?
The issue I am running into is that it doesn't seem like this is actually possible? When I call dothis("hey", "how are you", "good")
I was hoping it would set value to default to 0, but instead it is just making value="hey"
. Is there any way to accomplish this behavior?
推荐答案
这在 Ruby 中无法直接实现
This is not possible directly in Ruby
不过有很多选择,具体取决于您对扩展参数的处理方式以及该方法的用途.
There are plenty of options though, depending on what you are doing with your extended params, and what the method is intended to do.
明显的选择是
1) 使用哈希语法取命名参数
1) Take named params using hash syntax
def dothis params
value = params[:value] || 0
list_of_stuff = params[:list] || []
Ruby 对此有很好的调用约定,您不需要提供散列 {} 括号
Ruby has nice calling convention around this, you don't need to provide the hash {} brackets
dothis :list => ["hey", "how are you", "good"]
2) 将值移到最后,取数组作为第一个参数
2) Move value to the end, and take an array for the first param
def dothis list_of_stuff, value=0
这样称呼:
dothis ["hey", "how are you", "good"], 17
3) 使用代码块提供列表
3) Use a code block to provide the list
dothis value = 0
list_of_stuff = yield
这样称呼
dothis { ["hey", "how are you", "good"] }
4) Ruby 2.0 引入了命名散列参数,它为您处理了上面的很多选项 1:
4) Ruby 2.0 introduced named hash parameters, which handle a lot of option 1, above for you:
def dothis value: 0, list: []
# Local variables value and list already defined
# and defaulted if necessary
调用方式与 (1) 相同:
Called same way as (1):
dothis :list => ["hey", "how are you", "good"]
这篇关于Ruby 可选参数和多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!