Kris
Kris

Reputation: 19948

How to set a default value for a method argument

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?

Upvotes: 3

Views: 549

Answers (2)

asterite
asterite

Reputation: 2926

Use a default argument (like in 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

Usage of hashes for default/named arguments is totally discouraged in Crystal

(edited to include the sample instead of linking to the docs)

Upvotes: 7

Kris
Kris

Reputation: 19948

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.

Upvotes: 5

Related Questions