After creating a new Ruby OpenStruct object, I am able to store attributes but not to retrieve them (I get a blank line and it returns nil instead):
obj = OpenStruct.new # => #<OpenStruct>
obj.x = 10
obj.y = 20
obj # => #<OpenStruct x=10, y=20>
obj.x # => 10
obj.y #
# => nil
If I try to store other properties with different names, everything works as expected. This problem seems to happen only when I store a property named y. I’m using the following version:
ruby 1.9.2p320 (2012-04-20 revision 35421) [i686-linux]
Does anybody have an idea of what’s going on?
Something somewhere is pulling in
Psychfor YAML stuff. Psych patchesKernelto add apsych_ymethod which is aliased toy. So, everything has aymethod defined:AFAIK, OpenStruct uses
method_missingand an internal Hash to produce accessor and mutator methods; but, there’s already ayfrom that “friendly” patch to Kernel so OpenStruct’s magic doesn’t get to handle theymethod because Psych’s magic is in the way. The mutator,y=, is fine though so you can safelyo.y = 11and see your11insideo.You could remove the
ylike this:You could probably remove the method from
Kerneland hope that nothing depends on that sillyyalias:Or you could just remove it from
OpenStruct:This sort of thing is why a lot of people don’t like monkey patching, especially monkey patching something as fundamental as
Kernel.