如何为方法参数设置默认值

Kri*_*ris 3 crystal-lang

def my_method(options = {})
  # ...
end

# => Syntax error in ./src/auto_harvest.cr:17: for empty hashes use '{} of KeyType => ValueType'
Run Code Online (Sandbox Code Playgroud)

虽然这是有效的Ruby似乎不是在Crystal中,但我怀疑是因为打字.如何告诉编译器我想要默认为空哈希?

ast*_*ite 7

使用默认参数(如在Ruby中):

def my_method(x = 1, y = 2)
  x + y
end

my_method x: 10, y: 20 #=> 30
my_method x: 10        #=> 12
my_method y: 20        #=> 21
Run Code Online (Sandbox Code Playgroud)

在Crystal中完全不鼓励使用默认/命名参数的哈希值

(编辑后包含样本而不是链接到文档)


Kri*_*ris 5

似乎错误包含了我需要的所有信息,我需要指定键的类型和哈希的值.

def my_method(options = {} of Symbol => String)
  # ...
end
Run Code Online (Sandbox Code Playgroud)

文档中也很清楚.