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)
^
3 个解决方案
#1
20
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.
foo。bar= baz不是对方法栏的调用,而是对方法栏=的调用。你需要告诉send调用那个方法。
#2
3
Change the last line to:
将最后一行改为:
a.send(:c=, b.send(:c))
#3
1
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是一个动态变量,你可以这样做
c = 'my_key'
a.send("#{c}=", b.send(c))
#1
20
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.
foo。bar= baz不是对方法栏的调用,而是对方法栏=的调用。你需要告诉send调用那个方法。
#2
3
Change the last line to:
将最后一行改为:
a.send(:c=, b.send(:c))
#3
1
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是一个动态变量,你可以这样做
c = 'my_key'
a.send("#{c}=", b.send(c))