From: Robert Klemme Date: 2004-11-16T05:18:19+09:00 Subject: Re: OpenStruct#update ? "Florian Gross" schrieb im Newsbeitrag news:2vrtthF2n19d2U1@uni-berlin.de... > Robert Klemme wrote: > >> The singleton class of f knows about instance methods defined in super >> classes. Which is logical, considering this: > > Ah, I was confusing instance_methods() with instance_methods(false). > >>>accessors = h.keys - o.methods >>>class << o; self; end.send(:attr_accessor, *accessors) >>>h.each do |key, value| >>> o.send("#{key}=", value) if accessors.include?(key) >>>end >> >> Nice and short. But it has some drawbacks: >> [...] >> >> You would want ":bar" removed from the keys but it isn't because >> f.methods >> returns an array of String. (I assume that symbols are the most likely >> keys for the hash - which might be wrong.) > > Hm, I assumed the hash would contain Strings as keys. I guess it could be > normalized to that. I'd prefer symbols - partly because they are more memory efficient and partly because method id's are symbols, too. (Yeah, I know that all #methods returns strings and send() et. al can deal with strings, too. But I prefer to think of an identifier as a symbol rather as a string.) >> Plus, it's not selective enough IMHO because if you just have a setter, >> then that is overwritten. And if you just have a getter, then no setter >> is defined and you get an error during o.send("#{key}="...). > > I was trying to work around methods in Kernel -- I don't think it makes > sense to have o.p = when you don't have o.p. Well, normall not. But the other way round is more likely to occur, i.e., you don't have a setter but you have a getter. > But I guess the check isn't strictly needed anyway. (attr_accessor :p will > create a public getter. I thought it would create a private one.) Sorry, I'm not sure whether I understand what you mean here. Could you please explain a bit more? Kind regards robert