I’ve run into an instance in which I’d like to set attributes of an
instance using the send method. I’ve looked around, but found
nothing, most likely because I’m using the wrong search terms.
Example:
class A
attr_reader :foo
attr_writer :foo
end
a = A.new
a.send(“foo”, “newval”)
I get the following error: “wrong number of arguments (1 for 0)
(ArgumentError)”
Am I correct in thinking that this is possible, and that I’m just
going about it the wrong way?
I’ve run into an instance in which I’d like to set attributes of an
instance using the send method. I’ve looked around, but found
nothing, most likely because I’m using the wrong search terms.
[snip example]
I get the following error: “wrong number of arguments (1 for 0)
(ArgumentError)”
Am I correct in thinking that this is possible, and that I’m just
going about it the wrong way?
Yes.
…
The suspense almost killed me!
You need to use the setter method with #send - which happens to be
called “foo=” in your case.
Ah, now the lightbulb goes off. I should have remembered the
convention of having the setter have an equals sign as part of the
name. I’m too used to languages that determine which accessor is used
based on which side of the assignment it appears rather than actually
using a method name to syntactically simulate assignment.
On Fri, Oct 23, 2009 at 6:40 PM, Charles C. [email protected]
wrote:
…
name. I’m too used to languages that determine which accessor is used
based on which side of the assignment it appears rather than actually
using a method name to syntactically simulate assignment.
You can achieve what you want if instead of using attr_writer you roll
your own.
I remember a discussion in this list regarding something like:
class A
def a *args
return @a if args.empty? @a = args[0]
end
end
On 10/24/2009 09:06 AM, Jesús Gabriel y Galán wrote:
nothing, most likely because I’m using the wrong search terms.
The suspense almost killed me!
I’m glad I did not extend the pause even more.
You can achieve what you want if instead of using attr_writer you roll your own.
a.a #=> nil
a.a 4 #=> 4
a.a #=> 4
With this you can do a.send(:a, 4)
This also has the added advantage to be easier with #instance_eval, i.e.
you can then do
obj = A.new
obj.instance_eval do
a 10
end
If you had to use a= in the block you would have to write “self.a = 10”
in order to prevent recognition of “a” as a local variable.
Nevertheless, the general convention is to use a=. Btw, you could even
create a custom attr_accessor method that will create both variants so
you can do