0

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?

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You have to use dynamic message passing. Try this:

y.send :bike

Or, in your case

y.send x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.