user1449980
user1449980

Reputation: 49

How to access attribute which are stored as variables

model Sample has attributes car,bike

x ="bike"

y = Sample.new

How can I do?

y.x ?? It gives me an error Is there any way I can do it, I know that x is an attribute but I dont know which one.

So how can I get y.x?

Upvotes: 0

Views: 38

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

You have to use dynamic message passing. Try this:

y.send :bike

Or, in your case

y.send x

Upvotes: 0

user229044
user229044

Reputation: 239541

You can use send to invoke a method on an object when the method is stored as a string:

x = "bike"

y = Sample.new

y.send(x) # Equivalent to y.bike

The following are equivalent, except that you may send protected methods:

object.method_name
object.send("method_name")
object.send(:method_name)

Upvotes: 2

Related Questions