如何在Ruby中从方法动态分配属性

时间:2014-01-11 21:55:42

标签: ruby methods properties attributes variable-assignment

我有一个方法

def populate destination, source

end

其中目的地始终是以下值之一:“ax”,“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

这让我进入无休止的递归。

1 个答案:

答案 0 :(得分:2)

请尝试以下操作以删除错误:

 self.send(:populate,destination, source)

另见Object#send

  

调用符号标识的方法,并将指定的参数传递给 。如果名称发送与obj中的现有方法发生冲突,则可以使用__send__。当方法由字符串标识时,字符串将转换为符号。

<强>更新

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