Last Updated: September 09, 2019
·
904
· slawosz

Default value of hash (with nice examples)

Not everyone knows, that Hash class constructor in ruby can be used to initialize default value of hash.

For example, if our hash values will be arrays, instead of:

h       = {}
h[:foo] = []
h[:foo] << :bar

We can initialize hash in this way:

h = Hash.new { |key, value| key[value] = [] }
h[:foo] << :bar

That is much more ruby :)

And how you would return how many times each word is in some document (ie. array?):

I would write such code:

class Inc

    attr_reader :value

    def initialize
         @value = 0
    end

    def inc
        @value += 1
    end

    def inspect
        value
    end
end

h = Hash.new { |k,v| k[v] = Inc.new }

%(some array of words).each { |word| h[word].inc }

And now h stores words as keys and words counts in array as values.