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
A Hash is a collection of key-value pairs like this: "employee" = > "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.
The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.
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, *args, &blk) fetch(m) { fetch(m.to_s) { 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With