From: "trans. (T. Onoma)" Date: 2004-11-15T07:19:55+09:00 Subject: Re: OpenStruct#update ? On Sunday 14 November 2004 04:27 pm, David A. Black wrote: | > Why so conservative? So they don't overwrite standard object methods? I | > wondered why accessors weren't used. I suppose a hash is faster too. Hek, | > maybe '@' itself should be hash and forget about it ;) | | I'm assuming so. Actually here's what happens if you try: | | irb(main):020:0> o = OpenStruct.new | => | irb(main):021:0> o.class = 1 | => 1 | irb(main):022:0> o.class | => OpenStruct Ouch. I think that may be a bit too conservative. It's better that someone can shoot themselves in the foot rather than having someone else do it for them. I just got stung with: require 'yaml' q = YAML.load %Q{ --- x: 10 y: 20 ... } o = OpenStruct.new( q ) o.instance_eval { x } #=> 10 o.instance_eval { y } #=> nil | > | But I'm also not sure what you need to do that you can't do. The | > | OpenStruct object should let you add values indefinitely. | > | > This is what I mean: | > | > o = OpenStruct.new( foo_hash ) | > | > # later ... | > | > o.update( bar_hash ) | > | > The reason is because I am modifying and using the object on the fly. | | It's easy to write: | | o = OpenStruct.new({ :a => 1 }) | def o.update(h); h.each {|k,v| send("#{k}=",v)}; end | o.update({ :a => 2}) | p o.a | | # => 2 Cool. although I prefer to build it in. I looked at the ostruct.rb code. Very simple. All the "safety" logic is in #method_missing, so this is fine: require 'ostruct' class OpenStruct # Insert/update hash data on the fly. def update( hash ) if hash for k,v in hash @table[k.to_sym] = v end end end end Seems a reasonable addition to standard lib, yes? Thanks, T.