26 Feb 2008

Better code friendly hashes in Ruby with method_missing

I've previously posted on using method_missing to make friendly hashes in ruby.

Just thought I'd update it here with the ability to set values easily too.


class Hash
def method_missing(key, *args)
return self[key.to_s] if (args == nil || args.length == 0)
return self[key.to_s] = args[0]
end
end

name = {"title", "mr", "first", "craig", "last", "davidson"}

fullname = name.title, name.first, name.last
puts fullname.join " " # mr craig davidson

name.title "sgt"
name.first "george"
name.last "pepper"

fullname = name.title, name.first, name.last
puts fullname.join " " # sgt george pepper