Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: using Object.send for assigning variables

Tags:

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)             ^ 
like image 707
Sergey Avatar asked Jul 02 '10 17:07

Sergey


People also ask

How do you assign a variable in Ruby?

An instance variable must start with a @ (“at” sign or commercial at). Otherwise instance variable names follow the rules as local variable names. Since the instance variable starts with an @ the second character may be an upper-case letter. An uninitialized instance variable has a value of nil .

How do you pass a variable value in Ruby?

Ruby doesn't have any concept of a pure, non-reference value, so you certainly can't pass one to a method. Variables are always references to objects.

How do you use the send method in Ruby?

Ruby Language Metaprogramming send() methodsend() is used to pass message to object . send() is an instance method of the Object class. The first argument in send() is the message that you're sending to the object - that is, the name of a method. It could be string or symbol but symbols are preferred.


1 Answers

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.

like image 119
sepp2k Avatar answered Oct 12 '22 23:10

sepp2k