Sunday, July 28, 2013

Ruby - how to access properties using 'string' version of property-names

(2012 question/answer)
http://stackoverflow.com/questions/12136262/ruby-get-set-an-objects-property-using-a-string-symbol
car.color
car.send("color=", value)
(2009 question/answer)
http://stackoverflow.com/questions/903763/how-to-convert-from-a-string-to-object-attribute-name
irb> example_customer.name
#=> "Evagation Governessy"
irb> field = 'name'
#=> "name"
irb> example_customer.instance_variable_get(field)
NameError: `name` is not allowed as an instance variable name
from (irb):8:in `instance_variable_get`
from (irb):8
irb> example_customer.instance_variable_get('@'+field)
#=> nil
irb> example_customer.send(field)
#=> "Evagation Governessy"
irb> example_customer.send(field+'=', "Evagation Governessy Jr.")
#=> "Evagation Governessy Jr."
irb> example_customer.send(field)
#=> "Evagation Governessy Jr."
irb> example_customer.name
#=> "Evagation Governessy Jr."
So you can see how #send(field) accesses the record information, and trying to access the attributes doesn't. Also, we can use #send(field+'=') to change record information. 

No comments:

Post a Comment

Followers

Blog Archive