Pretty neat Mash class (Magic Hash)

class Mash < Hash
def method_missing(name, value=nil)
key = name.to_s.sub(/[=?!]$/,’’).to_sym
self[key] = value if name.to_s[-1,1] == “=”
self[key] = Mash.new unless self[key] || value
return self[key]
end
end

Its like OpenStruct…so what can you do?

require ‘pp’
m = Mash.new
m.first_name = “john”
m.last_name = “doe”
m.address.street = “somewhere drive”
m.address.city = “somecity”
m.address.state = “somestate”
m.address.zip = 12334
pp m

{:address=>
{:state=>“somestate”,
:street=>“somewhere drive”,
:city=>“somecity”,
:zip=>12334},
:first_name=>“john”,
:last_name=>“doe”}

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs