How to define the initial size of a hash?

Hi, I couldn’t find any example about it. How can I define the initial size of a hash?. This is the code:

myhash = {} of String => String
puts myhash.size

I would like to give space for 100 elements. I saw .new(initial_capacity) in the documentation but I don’t know how to apply it to the code.

You can’t use the literal syntax in this case. Would need to use that constructor method on the actual Hash type. E.g. Hash(String, String).new 100.

EDIT: Oh wait, there isn’t actually a method that only takes the initial size…
EDIT2: Prob would want to do something like this then:

Hash(String, String).new 100 do |_, key|
  raise "Missing hash key: #{key.inspect}"

Is there a reason there isn’t an overload that just takes the size and uses the default block?

1 Like

Thanks for the quick reply. Looks like this should work but I don’t how to see the size because it is always 0:

myhash = Hash(String, String).new(initial_capacity: 100)
puts myhash.size

Ohh you’re right, this overload supports it as the block is nil by default.

It does work but the capacity of the of the hash != its current size. I.e. the hash is empty because you just created it, but the internal buffer has support to store 100 strings before it needs to allocate more memory. If you didn’t specify the initial capacity, as you add more items to it, it would need to re-allocate more memory multiple times, which isn’t as efficient.


Thanks for the clarification!. I’m still too new to Crystal.