Automatically setting attributes

How can I do something like the following:

class Foo

    attr_accessor :goo, :moo

    def initalize
        @attr.each { | attrib| attrib = 0 }
    end
end

In case it's not clear, I want to set all attributes of the Foo object
to zero. But I can't seem to get the syntax for it correct.

Thanks,
Joe

Laughlin, Joseph V wrote:

How can I do something like the following:

class Foo

    attr_accessor :goo, :moo

    def initalize
        @attr.each { | attrib| attrib = 0 }
    end
end

In case it's not clear, I want to set all attributes of the Foo object
to zero. But I can't seem to get the syntax for it correct.

class Foo
   attr_accessor :goo, :moo

   def initialize
     methods.grep(/^\w+\=$/) {|m| send m, 0}
   end
end

f = Foo.new
p f # ==> #<Foo:0x401c6bec @goo=0, @moo=0>

~ > cat a.rb
   require 'yaml'

   class Klass
     ATTRIBUTES =
       %w(
         foo
         bar
         foobar
       )

     ATTRIBUTES.each{|a| attr a, true}

     def initialize
       attributes.each{|a| send "#{ a }=", 0}
     end

     def attributes
       ATTRIBUTES
     end

     def to_yaml(*args,&block)
       attributes.inject({}) do |h,a|
         h[a] = send a
         h
       end.to_yaml(*args,&block)
     end
   end

   obj = Klass.new
   y obj

   ~ > ruby a.rb

···

On Thu, 29 Jul 2004, Laughlin, Joseph V wrote:

How can I do something like the following:

class Foo

   attr_accessor :goo, :moo

   def initalize
       @attr.each { | attrib| attrib = 0 }
   end
end

In case it's not clear, I want to set all attributes of the Foo object
to zero. But I can't seem to get the syntax for it correct.

Thanks,
Joe

   ---
   foobar: 0
   foo: 0
   bar: 0

cheers.

-a
--

EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
PHONE :: 303.497.6469
A flower falls, even though we love it;
and a weed grows, even though we do not love it. --Dogen

===============================================================================

"Laughlin, Joseph V" <Joseph.V.Laughlin@boeing.com> schrieb im Newsbeitrag
news:67B3A7DA6591BE439001F27362333512030B09CA@xch-nw-28.nw.nos.boeing.com...

How can I do something like the following:

class Foo

    attr_accessor :goo, :moo

    def initalize
        @attr.each { | attrib| attrib = 0 }
    end
end

In case it's not clear, I want to set all attributes of the Foo object
to zero. But I can't seem to get the syntax for it correct.

How about:

class Foo
    attr_accessor :goo, :moo

    def initialize(h={})
        h.each {|k,v| send("#{k}=", v)}
    end
end

foo = Foo.new(:goo => 10, :moo => 20)

Regards

    robert