Created
September 26, 2012 16:57
-
-
Save gnarmis/3789174 to your computer and use it in GitHub Desktop.
Ruby Hashes as functions of keys to values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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