Crystal:方法选项的好方法
Crystal: a good way for method options
我需要将一些选项传递给方法,其中一些选项是可选的(类似于 JS 中的对象解构)。
我当前的代码:
def initialize( arg1 : String, options = {} of Symbol => String )
opt = MyClass.get_option options, :opt1
@opt1 = !opt.empty? ? opt : "Def value"
opt = MyClass.get_option options, :opt2
@opt2 = !opt.empty? ? opt : "False"
# ...
end
def self.get_option( options, key : Symbol )
( options && options[key]? ) ? options[key].strip : ""
end
我称之为:MyClass.new "Arg", { opt2: "True", opt4: "123" }
它有效,但我正在寻找更好的方法。设置每个选项的类型并直接在函数签名中设置默认值会很有用。
使用 NamedTuple 似乎是个好方法,但我遇到了可选值的问题 - options : NamedTuple( opt1: String, opt2: Bool, opt3: String, opt4: Int ) | Nil = nil
我尝试的另一种方法是使用结构,但它似乎使情况复杂化。
Crystal 具有可选和命名方法参数作为核心语言特性,并且不需要编写特殊代码来处理参数。请参阅有关 Method arguments 的官方文档。特别是,这里有一个例子:
def method(arg1 : String, *, opt1 = "Def value", opt2 = false)
星号并不总是需要的,它只确保以下可选参数只能按名称传递:
method("test", opt1: "other value", opt2: false)
我需要将一些选项传递给方法,其中一些选项是可选的(类似于 JS 中的对象解构)。
我当前的代码:
def initialize( arg1 : String, options = {} of Symbol => String )
opt = MyClass.get_option options, :opt1
@opt1 = !opt.empty? ? opt : "Def value"
opt = MyClass.get_option options, :opt2
@opt2 = !opt.empty? ? opt : "False"
# ...
end
def self.get_option( options, key : Symbol )
( options && options[key]? ) ? options[key].strip : ""
end
我称之为:MyClass.new "Arg", { opt2: "True", opt4: "123" }
它有效,但我正在寻找更好的方法。设置每个选项的类型并直接在函数签名中设置默认值会很有用。
使用 NamedTuple 似乎是个好方法,但我遇到了可选值的问题 - options : NamedTuple( opt1: String, opt2: Bool, opt3: String, opt4: Int ) | Nil = nil
我尝试的另一种方法是使用结构,但它似乎使情况复杂化。
Crystal 具有可选和命名方法参数作为核心语言特性,并且不需要编写特殊代码来处理参数。请参阅有关 Method arguments 的官方文档。特别是,这里有一个例子:
def method(arg1 : String, *, opt1 = "Def value", opt2 = false)
星号并不总是需要的,它只确保以下可选参数只能按名称传递:
method("test", opt1: "other value", opt2: false)