class MyOpenStruct < BasicObject
def initialize(initial_values = {})
@values = initial_values
end
def _singleton_class
class << self
self
end
end
def method_missing(name, *args, &block)
if name[-1] == "="
base_name = name[0..-2].intern
_singleton_class.instance_exec(name) do |name|
define_method(name) do |value|
@values[base_name] = value
end
end
@value[base_name] = args[0]
else
#super unless @values.has_key? name
_singleton_class.instance_exec(name) do |name|
define_method(name) do
@values[name]
end
end
@values[name]
end
end
end
my = MyOpenStruct.new(name: "chenchao")
my.address = "beijing"
my.likes = "beauty girl"
puts "#{my.name} lives in #{my.address} , likes #{my.likes}"
执行收到错误信息是
/home/stephan/work/test/hook.rb:61:in method_missing': undefined method
[]=' for nil:NilClass (NoMethodError)
from /home/stephan/work/test/hook.rb:74:in `