Forum: Ruby on Rails Accessing attributes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
26960e68378bc217eeb4e08b71e07fad?d=identicon&s=25 r00by n00by (Guest)
on 2006-01-29 21:39
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?
2ccb2f7699267d258faaafce4ee997df?d=identicon&s=25 Cody Fauser (Guest)
on 2006-01-30 00:21
(Received via mailing list)
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 <ul1c7x7o60zuqnd@jetable.org> wrote:
>
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> Rails mailing list
> Rails@lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>


--
Cody Fauser
http://www.codyfauser.com
This topic is locked and can not be replied to.