We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
a few points to keep in mind:
Use {} for a normal hash. Hash.new(0) works well for counters. Avoid Hash.new([]) since it shares the same array, instead use Hash.new { |h, k| h[k] = [] } to create separate arrays. For nested counters, you can try Hash.new { |h, k| h[k] = Hash.new(0) }. You can also build a hash from key-value pairs with Hash[...].
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Ruby Hash - Initialization
You are viewing a single comment's thread. Return to all comments →
a few points to keep in mind: Use {} for a normal hash. Hash.new(0) works well for counters. Avoid Hash.new([]) since it shares the same array, instead use Hash.new { |h, k| h[k] = [] } to create separate arrays. For nested counters, you can try Hash.new { |h, k| h[k] = Hash.new(0) }. You can also build a hash from key-value pairs with Hash[...].