How to set a default value for a method argument

时间:2015-07-28 22:32:34

标签: crystal-lang

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

# => Syntax error in ./src/auto_harvest.cr:17: for empty hashes use '{} of KeyType => ValueType'

While this is valid Ruby it seems not to be in Crystal, my suspicion is that it is because of typing. How do I tell compiler I want to default to an empty hash?

2 个答案:

答案 0 :(得分: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

在Crystal

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

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

答案 1 :(得分:5)

It seems the error has all the information I needed, I need to specify the type for the key and values of the Hash.

def my_method(options = {} of Symbol => String)
  # ...
end

It is quite clearly in the docs too.