Thursday, June 3, 2010

Allowing hash values to be set and retrieved as if they were attributes

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. 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 we are going to use is Kernel's method_missing.

Here we are opening the class Hash :-



And this is the sample output :-

h = Hash.new("The key does not correspond to any hash entry")
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

No comments:

Post a Comment