Here is my remix on sepp2k. This is a bit more OO and works even in irb . Not sure if you need to schedule an 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
OpenStruct : thanks sepp2k again! I did not know this one .
Here is 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 can get the code more rigorous (if I knew how to do this).
source share