/
README
57 lines (36 loc) · 1.19 KB
/
README
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Author
====
Niranjan Sarade
About the utility - HashKeyAsAttribute
====
In ruby, we have OpenStruct which allows the creation of data objects with arbitrary attributes.
With ruby's metaprogramming capability, we can also allow hash values to be set and retrieved as if
they were its attributes. So setting and getting the value for the key would be treated as if they
were method calls on the hash object.
If the key does not correspond to any hash entry, it should return “The key does not correspond to any hash entry” message.
The hook that has been used is Kernel's method_missing.
Example
====
require 'hash_key_as_attribute'
h = {}
h.one = 1
puts h.one #=> 1
h.two= [1,2,3,4]
puts h.two.inspect #=> [1,2,3,4]
puts h.three #=> "The key does not correspond to any hash entry"
puts h.inspect #=> {:one=>1, :two=>[1, 2, 3, 4]}
h2 = {}
h2.four = 4
h.three = h2
puts h.three.inspect #=> {:four=>4}
puts h.three.four #=> 4
Install
====
gem install hash_key_as_attribute
(It has been pushed to http://gemcutter.org)
OR
Download the gem file from http://github.com/NiranjanSarade/hash_key_as_attribute/
gem install hash_key_as_attribute-0.0.1.gem
Uninstall
====
gem uninstall hash_key_as_attribute