Skip to content

Instantly share code, notes, and snippets.

@gnarmis
Created September 26, 2012 16:57
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 gnarmis/3789174 to your computer and use it in GitHub Desktop.
Save gnarmis/3789174 to your computer and use it in GitHub Desktop.
Ruby Hashes as functions of keys to values
# In Clojure, hash-maps are truly functions of keys to values.
# So you can do `(:a {:a 1})` and get `1` as the result
# Why not put this in Ruby?
# access keys of a hash like a function
class Object
def respond_to?(method)
if (method.to_s =~ /^_.*/) == 0
true
else
super
end
end
def method_missing(name, *args, &b)
if (args.count==1) && b.nil? && name[0]=="_" &&
args[0].has_key?(name[1..-1].to_sym)
args[0][name[1..-1].to_sym]
else
super
end
end
end
hash = {:a => 1}
(_a hash) == 1 #=> true
(_a hash) == (hash [:a]) #=> true
# the underscore serves to prevent naming conflicts to a degree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment