Sreeraj Sreeraj - 5 months ago 16
Ruby Question

How do I convert hash keys to method names?

This is my hash:

tempData = {"a" => 100, "here" => 200, "c" => "hello"}


I need to access the hash keys as a method like:

tempData.a #100
tempData.here # 200

Answer

You could just wrap up your hash in an OpenStruct:

require 'ostruct'
tempData = {"a" => 100, "here" => 200, "c" => "hello"}
os = OpenStruct.new tempData
os.a #=> 100
os.here #=> 200

If you really really wanted to, you could also monkey-patch the Hash class, but I'd advise against that:

class Hash
  def method_missing(m)
    key = m.to_s
    return self[key] if self.has_key? key
    super
  end
end

tempData = {"a" => 100, "here" => 200, "c" => "hello"}
tempData.a #=> 100

Update: In my personal extensions library I added a Hash#to_ostruct method. This will recursively convert a hash into an OpenStruct including all nested hashes.