I'm trying to solve a problem where I want to use hash to record the indices of each character appeared in the array.
def dupe_indices(arr)
hash = Hash.new {|h,k| []}
arr.each.with_index do |char,idx|
hash[char] << idx
end
return hash
end
Weird thing is that, despite hash[char] will initialize as empty array, hash[char] << idx won't work. The hash will end up empty: {}.
I can fix the issue by either initializing the hash using Hash.new {|h,k| h[k] = []} or changing hash[char] << idx to hash[char] = hash[char].push[idx] for assignment.