wconrad / yagni.com wrote in message news:<20020503220050.GA443 / pluto>...
> This way, which is probably not the best way, seems to do something:
> 
> wconrad@pluto:~/lab/foo1$ cat foo.rb
> #!/usr/bin/ruby
> 
> class Foo
>   
>   def initialize(hash)
>     for key, value in hash do
>       eval "@#{key}=#{value.inspect}"
>     end
>   end
> 
> end
> 
> p Foo.new({"i"=>1, "s"=>"blah"})


Someone else will probably give you a better solution, but here's
something I wrote that avoids a problem I see with the 'value.inspect'
method.  The issue is that often the string version of an object cannot
be used to assign to a variable and end up with the same type as the
original.

With the inspect version, I don't think, for example, that assigning
a time value would work.  Anyway, have a play with this one if you're
interested.  It also has the advantage that it uses method_missing to
provide setters and getters for all the instance variables.

class HashStruct

    def initialize(hash)
        hash.each_pair do |key, value|
            instance_eval "@#{key} = value"
        end
    end

    def method_missing(name, *args)
        if name.to_s =~ /(.*)=/
            self.instance_eval "@#{$1} = args[0]"
        else
            self.instance_eval "@#{name}"
        end
    end

end

hs = HashStruct.new({"text" => "hello", "time" => Time.now})

$stderr.puts hs.text
$stderr.puts hs.time

sleep 2

hs.time = Time.now

$stderr.puts hs.time