有没有办法在Crystal中使用带有splat运算符的非元组对象?

Mik*_*eev 2 splat crystal-lang

是否有一些函数或语法结构使下一个例子有效?

Hash#values_at使用Array参数调用函数:

h = {"a" => 1, "b" => 2, "c" => 3}
ary = ["a", "b"]
h.values_at(*ary) # Error: argument to splat must be a tuple, not Array(String)
Run Code Online (Sandbox Code Playgroud)

传递Hash给初始化类或结构:

struct Point                                                                                                 
    def initialize(@x : Int32, @y : Int32)                                                                     
    end                                                                                                        
end
h = {"x" => 1, "y" => 2}
Point.new(**h) # Error: argument to double splat must be a named tuple, not Hash(String, Int32)
Run Code Online (Sandbox Code Playgroud)

Jon*_*Haß 5

根据具体情况,第一个例子可能是不可能的.但是,如果元素的长度是固定的,您可以这样做:

h = {"a" => 1, "b" => 2, "c" => 3}
ary = ["a", "b"]
p h.values_at(*{String, String}.from(ary))
Run Code Online (Sandbox Code Playgroud)

https://carc.in/#/r/3oot参见Tuple.from

NamedTuple 支持相同的方法:

struct Point                                                                                                 
    def initialize(@x : Int32, @y : Int32)                                                                     
    end                                                                                                        
end
h = {"x" => 1, "y" => 2}

p Point.new(**{x: Int32, y: Int32}.from(h))
Run Code Online (Sandbox Code Playgroud)

https://carc.in/#/r/3oov请参阅NamedTuple.from

这些只是确保类型和在运行时手动分解结构的一些糖,主要用于数据来自外部源,例如从JSON解析.

当然,这是首选创建和使用TupleArrayNamedTupleHash哪里可以摆在首位.