Tutorial :Ruby: using Object.send for assigning variables


Is there any way to do something like this?

a = Struct.new(:c).new(1)  b = Struct.new(:c).new(2)    a.send(:c)  => 1    b.send(:c)  => 2    a.send(:c) = b.send(:c)  

The last line result in error:

syntax error, unexpected '=', expecting $end  a.send(:c) = b.send(:c)              ^  


a.send(:c=, b.send(:c))  

foo.bar = baz isn't a call to the method bar followed by an assignment - it's a call to the method bar=. So you need to tell send to call that method.


Change the last line to:

a.send(:c=, b.send(:c))  


If you know the variable name beforehand

a.send(:c=, b.send(:c))  

If c is a dynamic variable then you can do it like this

c = 'my_key'  a.send("#{c}=", b.send(c))  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »