Avoid Hashy Syntax In Ruby

A way to nip PrimitiveObsession in the bud, with RubyLanguage:

Instead of doing things like:

obj = {}
        obj[:prop] = 3
        puts obj[:prop]

One can do something like:

        require 'ostruct'
        …
obj = OpenStruct.new
        obj.prop = 3
        puts obj.prop

This is a nice first-step on the way to a proper class, because this is basically a direct transliteration, whereas the step where you start adding richer methods is trickier (and we wouldn't want to conflate the two changes into one refactoring step, if possible).

Note that you can actually implement the '[]' method on proper classes, meaning you can still avoid conflating the two steps into one, even if you do them in the other order. RubyIsFun?.


EditText of this page (last edited February 18, 2013) or FindPage with title or text search