Accessing attributes

I have a name of an attribute and I need to get its value and set a new
value for it:

x1 = a.foo
a.foo = x2

How do I do that if the name of the attribute ‘foo’ is a var?
I thought about doing this:

attribute_name = ‘foo’

x1 = a.attributes[attribute_name]
a.attributes[attribute_name] = x2

but this is a bypass and I’m quite sure it would cause problems.
I know I could use ‘eval’, but I’d rather use it only as the last
option.
Is there a bette option?

You could try this:

attr = ‘name’

get the attribute

a.send(attr)

set the attribute

a.send("#{attr}=", “New Name”)

On 1/29/06, r00by n00by [email protected] wrote:

Posted via http://www.ruby-forum.com/.


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails


Cody F.
http://www.codyfauser.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs