Skip to content

Instantly share code, notes, and snippets.

@mrflip
Created April 27, 2011 01:15
Show Gist options
  • Save mrflip/943543 to your computer and use it in GitHub Desktop.
Save mrflip/943543 to your computer and use it in GitHub Desktop.
Fun with blocks -- a couple things you might be glad to find out Ruby can do
#
# When you're using inject with a hash or somesuch, you can subgroup the source's elements:
#
# v--- the parens part here
{ 1 => 2, 3 => 4, :your => :mom }.inject({}) do |h, (k,v)|
h[k] = v**2 if v.is_a?(Numeric)
h
end
# => {1=>4, 3=>16}
# You can make an autovivifying hash by passing a block to Hash.new:
h = Hash.new{|h,k| h[k] = 0 }
# => {}
h[:your_mom]
# => 0
h
# => {:your_mom=>0}
# This makes it easy to count objects:
[:a, :b, :c, :d, :e, :c, :b, :d, :a, :b].inject(Hash.new{ 0 }){|h, val| h[val] += 1 ; h }
# => {:a=>2, :b=>3, :c=>2, :d=>2, :e=>1} # 2 a's, c's, and d's; 3 b's and 1 e.
# or build Trees:
class Tree < Hash
def initialize(*args)
super(*args){|h,k| h[k] = Tree.new }
end
end
# => nil
h = Tree.new
h[:a][:b][:c] = 1
# => 1
h
# => {:a=>{:b=>{:c=>1}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment