Robert Klemme
10/23/2008 6:03:00 AM
On 23.10.2008 01:42, Martin DeMello wrote:
> On Wed, Oct 22, 2008 at 4:34 PM, David A. Black <dblack@rubypal.com> wrote:
>> Do you need to use inheritance, as opposed to just instantiating
>> MyStruct directly? I'm thinking of, for example:
>>
>> class MyStruct < Struct
>> def self.new(*keys)
>> s = super
>> s.class_eval do
>> define_method(:initialize) do |hash|
>> hash.each {|k,v| send("#{k}=",v) }
>> end
>> end
>> s
>> end
>> end
>
> Doh - of course, since you aren't inheriting from Struct, you
> shouldn't be inheriting from MyStruct either :) Wasn't thinking
> clearly enough about the problem. Thanks!
Why inheritance at all? Why do too much?
irb(main):001:0> MyStruct = Struct.new :foo, :bar do
irb(main):002:1* def initialize(h={})
irb(main):003:2> members.each {|m| self[m] = h[m.to_sym]}
irb(main):004:2> end
irb(main):005:1> end
=> MyStruct
irb(main):006:0> ms = MyStruct.new(:bar => 1, :foo => 2)
=> #<struct MyStruct foo=2, bar=1>
Kind regards
robert