I have an object that is using attr_accessor. I want to be able to call a method on that object with a variable with #send. My problem is that the = method doesn't seem to work.
class Foo
attr_accessor :bar
end
class Test_class
def test_method(x)
f = Foo.new
f.send(x)
f.send(x) = "test" #this doesnt work
f.send("#{x} =") "test" #this also doesn't work
# How can I set bar?
end
end
t = Test_class.new
t.test_method("bar")
You want
f.send "#{x}=", "test". In Ruby, method names may include punctuation, such as=or!. The methods created byattr_accessor :barare simply namedbarandbar=. In fact,attr_accessor :baris just shorthand for:When you're calling
foo.bar = "baz", you're actually calling the#bar=method withfooas the receiver and"bar"as the first parameter to the function - that is,foo.bar=("baz"). Ruby just provides syntactic sugar for methods ending in=so that you can write the more natural-looking form.