Hash sugar 3

Posted by jeff Tuesday, July 25, 2006 18:27:00 GMT

Ruby sure is spoiling me. Today I got tired of the hash syntax when the keys are all strings:

h = {}
h["cart"] = Cart.new
h["products] = customer.products
h["days"] = [:monday, :tuesday]

instead I decided that I’m too lazy to type all those extra quotes and brackets.

So I opened up the Hash class and just did this:

class Hash
 def method_missing(m, *args)
   if (m.to_s =~ /=$/)
     store(m.to_s[0..-2], *args)
   else
     self.[](m.to_s)
   end
 end
end

Now I can write code like this instead:

h = {}
h.cart = Cart.new
h.products = customer.products
h.days = [:monday, :tuesday]

Looks more like a regular object to me this way.

Warning, you can’t store non-string or non-symbol keys in the hash anymore. So h4 = 6 won’t work. But I’m just storing strings in this hash, so this works for me.

Comments

Leave a response

  1. SC   July 25, 2006 @ 08:16 PM

    How about using the OpenStruct class instead:

    http://rubymanual.org/class/OpenStruct

    require 'ostruct'
    
    record = OpenStruct.new
    record.name    = "John Smith"
    record.age     = 70
    record.pension = 300
    
    puts record.name     # -> "John Smith"
    puts record.address  # -> nil
    
  2. kino   May 24, 2008 @ 01:12 AM

    The fact is that, by reconciling with the fundamental form of this universal synthesis, I, the meditating phenomenologist, set myself the all-embracing task of uncovering myself by orienting cognition according to accured insights.

  3. Ellroy   May 30, 2008 @ 11:19 PM

    By virtue of pure reason, it must not be supposed that, irrespective of all empirical conditions, the Ideal of human reason would thereby be made to contradict our sense perceptions, but the Transcendental Deduction can never furnish a true and demonstrated science, because, like the manifold, it would thereby be made to contradict disjunctive principles.

Comment


(won't be published)