Skip to content

Instantly share code, notes, and snippets.

@bmc
Created February 7, 2011 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmc/813967 to your computer and use it in GitHub Desktop.
Save bmc/813967 to your computer and use it in GitHub Desktop.
Screwing around with a CallableHash class in Ruby
class CallableHash < Hash
def initialize(h)
h.each do |k, v|
self[k] = v
end
@@methods = {}
end
def respond_to?(sym)
true
end
def method_missing(sym, *args, &block)
proc = @@methods[sym]
if ! proc
name = sym.to_s
if string_ends_with?(name, '=')
key = name[0..-2]
proc = Proc.new {|v| self[key.to_sym] = v}
else
proc = Proc.new {self[sym]}
end
end
proc.call(*args)
end
def get_binding
binding()
end
private
def string_ends_with?(s, sub)
tail = s[-sub.length, sub.length]
tail == sub
end
end
h = CallableHash.new(:a => 1, :b => 2)
puts(h.inspect) # {:a=>1, :b=>2}
puts(h[:a]) # 1
h[:a] = 2
puts(h[:a]) # 2
puts(h.a) # 2
h.a = 3
puts(h.a) # 3
puts(h["a"]) # nil
h['a'] = 10
puts(h["a"]) # 10
puts(h.inspect) # {"a"=>10, :a=>3, :b=>2}
h.delete(:a)
puts(h[:a]) # nil
puts(h.a) # nil
h.a = 'foo'
puts(h.inspect) # {"a"=>10, :b=>2, :a=>"foo"}
puts(h.a) # foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment