Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Get/set an object's property using a string/symbol

Tags:

ruby

In Ruby, how can I get and set a property of an object using a string/symbol?

For example, if I have an object car with properties car.color and car.name.

I know you can do car.send(:color) to get its property, but how can I set it?

like image 863
Calvin Avatar asked Aug 27 '12 04:08

Calvin


People also ask

Can an object property be a string?

Property keys must be strings or symbols (usually strings). Values can be of any type.

What does '?' Mean in Ruby?

i know that the '?' in ruby is something that checks the yes/no fulfillment.

What is the difference between string and Symbol in Ruby?

There are two main differences between String and Symbol in Ruby. String is mutable and Symbol is not: Because the String is mutable, it can be change in somewhere and can lead to the result is not correct. Symbol is immutable.


1 Answers

car.send("name=", value) 

Or

car.send("color=", value) 
like image 120
Candide Avatar answered Sep 19 '22 01:09

Candide