Skip to content

Instantly share code, notes, and snippets.

@puyo
Forked from juliocesar/hashblock.rb
Created April 14, 2010 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save puyo/365753 to your computer and use it in GitHub Desktop.
Save puyo/365753 to your computer and use it in GitHub Desktop.
# What is it with you people and your singletons?
class Hash
def self.from_block(&block)
Hash[*BlockBuilder.new(&block).collected]
end
class BlockBuilder
attr_reader :collected
def initialize(&block)
@collected = []
instance_eval(&block)
end
def method_missing(method, *args)
@collected << method.to_sym << args.first
end
end
end
p Hash.from_block { apple 8; banana 2; carrot 6 }
# prints {:apple=>8, :banana=>2, :carrot=>6}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment