Skip to content

Instantly share code, notes, and snippets.

@Sutto
Created June 7, 2013 01:58
Show Gist options
  • Save Sutto/5726597 to your computer and use it in GitHub Desktop.
Save Sutto/5726597 to your computer and use it in GitHub Desktop.
# First: Product - Default without setting hash defaults:
x = %w(a b c)
h = Hash[x.product([true])]
p h # => {'a' => true, 'b' => true, 'c' => true}
p h['a'] # => true
p h['d'] # => nil
# e.g: sphinx takes a hash of field name -> weight pairs, so we use
def search_weights
@search_weights ||= Hash[fields.product([25]) + sanitized_fields.product([1])]
end
# to generate the hash.
# Second: normal default
i = Hash.new(false)
p i # => {}
p i['a'] # => false
p i # => {}
# With a block
j = Hash.new { |h,k| h[k] = false }
p i # => {}
p i['a'] # => false
p i # => {'a' => false}
# Now, doing magic! - Super useful for data munging.
k = Hash.new { |h,k| h[k] = [] }
%w(a b c d).each_with_index do |key, idx|
k[key] << idx
end
p k # => {"a"=>[0], "b"=>[1], "c"=>[2], "d"=>[3]}
# And, for the grand finale:
k = Hash.new { |h,k| h[k] = Hash.new(&h.default_proc) }
p k # => {}
p k[:a][:b][:c] # => {}
p k # => {:a=>{:b=>{:c=>{}}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment