Can I access an object attribute dynamically using a variabl

Not sure exactly how to put this, but I want to assign a value to an
attribute of an object (e.g. part.partnumber) using a dynamic name for
the attribute (a variable of type String). It seems like I should be
able to, but I can’t seem to figure it out. Any help would be
appreciated. Here’s some code to illustrate what I have tried so far…

Create a field name and find a part

fieldname = “partnumber”
part = Part.find(params[:id])

Try to access an attribute using the dynamic field name

I actually want an assignment, but logging is an adequate example

logger.info(part.fieldname) #NOPE
logger.info(part[fieldname]) #NOPE
logger.info(part["’" + fieldname + “’”]) #NOPE
logger.info(part[":" + fieldname]) #NOPE

On Sep 21, 2006, at 12:13 PM, Nathan L. wrote:

Try to access an attribute using the dynamic field name

I actually want an assignment, but logging is an adequate example

logger.info(part.fieldname) #NOPE
logger.info(part[fieldname]) #NOPE
logger.info(part["’" + fieldname + “’”]) #NOPE
logger.info(part[":" + fieldname]) #NOPE

part.send fieldname

-Ezra

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