2014-01-11 29 views
0

指派属性我有一个方法如何动态地从法红宝石

def populate destination, source 

end 

其中目的地始终是以下值之一:“斧”,“BX”,“CX”,“DX” 。在包含该方法的类中,我有@ax,@ bx,@cx,@dx。如果目标动态变化,并且我知道它在方法主体中的运行时间,如何从方法主体分配正确的属性(属性)。

我是用试图发送方法是这样的:

self.send(destination, source) 

,但它给了我一个错误。

我已经定义的属性是这样的:

attr_accessor :ax, :bx, :cx, :dx 

编辑:

的方法本身:

def populate destination, source 
     receiver = destination 
     if source == :ax then self.send(:populate, receiver , @ax_real) end 
     if source == :bx then self.send(:populate, receiver , @bx_real) end 
     if source == :cx then self.send(:populate, receiver , @cx_real) end 
     if source == :dx then self.send(:populate, receiver , @dx_real) end 
     if source.class != Symbol then self.send(:populate, receiver , source) end 
end 

这使我陷入无限递归。

+0

你在这里要做什么'if source ==:ax then self.send(:populate,receiver,@ax_real)end'? –

+0

你正在试着做@ @ = = ax @,@ @ @ = = bx等等,,? –

+0

如果source是:ax那么我想设置来自目的地(ax,bx,cx,dx)的属性值并将其赋值为另一个属性@ax_real的值。 例如如果接收者是:cx我想要这个'@cx_real'='@ax_real'。 – user2128702

回答

2

尝试下面删除错误:

self.send(:populate,destination, source) 

看也Object#send

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj. When the method is identified by a string, the string is converted to a symbol.

更新

def populate destination, source 
    if source == :ax then send(:ax= ,@ax_real) end 
    if source == :bx then send(:bx= , @bx_real) end 
    if source == :cx then send(:cx= , @cx_real) end 
    if source == :dx then send(:dx= , @dx_real) end 
end 

做重新分解

def populate destination, source 
    send("#{source}=",instance_eval("@#{source}_real")) 
end 
+0

但是为什么我必须在self.send中传递方法'填充'的名称?当我跳过它,它给了我ArgumentError。 – user2128702

+0

@ user2128702查看我链接的方法文档。 –

+0

当我在代码中像这样使用它时,我进入堆栈过滤。也许有一个递归继续调用方法本身。这就是为什么我想知道我在填充方法本身内部执行self.send(:populate,destination,source)。 – user2128702