Question

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")
Was it helpful?

Solution

You want f.send "#{x}=", "test". In Ruby, method names may include punctuation, such as = or !. The methods created by attr_accessor :bar are simply named bar and bar=. In fact, attr_accessor :bar is just shorthand for:

def bar
  @bar
end

def bar=(value)
  @bar = value
end

When you're calling foo.bar = "baz", you're actually calling the #bar= method with foo as 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top