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 to share