Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert hash keys to method names?

Tags:

ruby

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 
like image 351
Sreeraj Avatar asked Jun 21 '11 09:06

Sreeraj


People also ask

What is Hash in Ruby on rails?

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.

What is key and value in Hash?

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.


1 Answers

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.

like image 121
Michael Kohl Avatar answered Sep 19 '22 07:09

Michael Kohl