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!
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.
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.
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.
attr_accessor is used to define an attribute for object of Model which is not mapped with any column in database.
I am not a ruby expert, but I think that you could do:
instance.send("a=", "value")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With