Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically call accessor methods in Ruby [duplicate]

Tags:

ruby

Regardless of whether it's good practice or not, how can I dynamically call accessor methods in Ruby?

Here's an example class:

class Test_Class   attr_accessor :a, :b end 

I can use the Object.send method to read the variable...

instance.a = "value" puts( instance.send( "a" ) ) # => value 

But I'm having a hard time trying to write to it. These throw "wrong number of arguments (1 for 0) (ArgumentError)"

instance.send("a", "value") 

and

instance.method("a").call("value") 

Please help me StackOverflow!

like image 479
Joe Zack Avatar asked Mar 07 '09 02:03

Joe Zack


People also ask

How do you call a method dynamically in Ruby?

Fortunately, Ruby's metaprogramming feature allows us to call methods dynamically by just passing the method name into public_send(method_name) or send(method_name) . We can call the make_noise method by calling Duck. new. public_send("make_noise") , this is equivalent to calling Duck.

How do you call a dynamic method?

In the dynamic method call, the parameters are not passed in parentheses. The syntax of the dynamic method call is like that of a function module call. The CALL_METHOD statement should now only be used for the dynamic method call. It is unnecessary, and therefore obsolete, for the static method call.

What does attr_ reader do in Ruby?

attr_reader and attr_writer in Ruby allow us to access and modify instance variables using the . notation by creating getter and setter methods automatically. These methods allow us to access instance variables from outside the scope of the class definition.

What does attr_ accessor do?

attr_accessor is used to define an attribute for object of Model which is not mapped with any column in database.


1 Answers

I am not a ruby expert, but I think that you could do:

instance.send("a=", "value") 
like image 70
Angela Avatar answered Sep 28 '22 19:09

Angela