How to set default value for 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 true, Ruby doesn't seem to be in Crystal, I suspect it is because of the input. How do I tell the compiler that I want to use an empty hash by default?

+3


source to share


2 answers


Use the 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

      



Using hashes for / named default arguments is completely discouraged in Crystal

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

+7


source


The error seems to have all the information it needs, I need to specify the key type and hash values.

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

      



This is clearly visible in the docs .

+5


source







All Articles