Automatically setting attributes

L

Laughlin, Joseph V

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
 
J

Joel VanderWerf

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>
 
A

Ara.T.Howard

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

~ > 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
---
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
===============================================================================
 
R

Robert Klemme

Laughlin said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,151
Messages
2,570,854
Members
47,394
Latest member
Olekdev

Latest Threads

Top