Here is my remix of sepp2k's answer. It's a bit more OO and works even in irb
. Not sure whether to patch Object
or Hash
.
class Hash
def keys_to_methods()
each do |k,v|
self.class.send(:define_method, k, Proc.new {v});
end
length
end
end
Test code
hash = {:color_one=>"black", :color_two=>"green"}
hash.keys_to_methods
has.color_one # returns black
OpenStruct: thanks to sepp2k again! I didn't know this existed.
Here is yet another version using method_missing
class Hash
def method_missing(method_id)
key = method_id.id2name
if has_key?(key)
return self[key]
elsif has_key?(key.to_sym)
return self[key.to_sym]
else
super.method_missing(method_id)
end
end
end
hash = {:color_one=>"black", :color_two=>"green"}
hash.color_one
I'm sure I could get the code tighter (if I knew how).