Sreeraj Sreeraj - 1 year ago 92
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 # 200

Answer Source

You could just wrap up your hash in an OpenStruct:

require 'ostruct'
tempData = {"a" => 100, "here" => 200, "c" => "hello"}
os = tempData
os.a #=> 100 #=> 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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download