Search code examples
crystal-lang

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?


Solution

  • 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)