class OpenStruct
def initialize
@attributes = {}
end
def method_missing(name,*args)
attribute = name.to_s
if attribute =~ /=$/
@attributes[attribute.chop] = args[0]
else
@attributes[attribute]
end
end
end
test = OpenStruct.new
test.power = "fdde"
test.power # => "fdde"
看《ruby元编程》中的例子;定义一个开放结构类,美妙的编程体验。