Skip to content

Instantly share code, notes, and snippets.

@dsturnbull
Forked from puyo/hashblock.rb
Created April 14, 2010 22:43
Show Gist options
  • Save dsturnbull/366436 to your computer and use it in GitHub Desktop.
Save dsturnbull/366436 to your computer and use it in GitHub Desktop.
def Hash(*args, &block)
if args.any?
args[0]
else
Hash.from_block &block
end
end
class Hash
def self.from_block &block
Hash[*BlockBuilder.build(&block)]
end
class BlockBuilder
@@collected = []
class << self
def build(&block)
instance_eval &block
copy = @@collected.clone and @@collected.clear and return copy
end
def method_missing(method, *args)
@@collected.concat [method.to_sym, args.first]
end
end
end
end
# Hash.from_block do
# apple 8
# banana 2
# carrot 6
# end
# => {:apple=>8, :banana=>2, :carrot=>6}
# specs
require 'rubygems'
require 'spec'
def test_hash(h)
h.keys.should include :apple
h[:apple].should == 8
h.keys.should include :banana
h[:banana].should == 2
h.keys.should include :carrot
h[:carrot].should == 6
end
describe Hash do
it 'should create a hash from a block' do
h = Hash.from_block do
apple 8
banana 2
carrot 6
end
test_hash(h)
end
it 'should create a hash from a block Hash { } syntax' do
h = Hash do
apple 8
banana 2
carrot 6
end
test_hash(h)
end
it 'should create a hash from a block with succinct syntax' do
h = Hash({ :apple => 8, :banana => 2, :carrot => 6 })
test_hash(h)
end
it 'should not be necessary to even have this class at all' do
h = { :apple => 8, :banana => 2, :carrot => 6 }
test_hash(h)
end
it 'is even better in ruby 1.9' do
h = { apple: 8, banana: 2, carrot: 6 }
test_hash(h)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment