【问题标题】:How to dynamically assign property from method in Ruby如何从Ruby中的方法动态分配属性
【发布时间】:2014-01-30 20:20:02
【问题描述】:

我有办法

def populate destination, source

end

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

我正在尝试这样的 send 方法:

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

这让我陷入了无休止的递归。

【问题讨论】:

  • 你想在这里做什么if source == :ax then self.send(:populate, receiver , @ax_real) end
  • 你是在尝试做@ax= :ax,@bx= :bx等吗?
  • 如果源是 :ax 那么我想设置来自目标的属性值(ax, bx, cx, dx) 并将其分配给另一个属性@ax_real 的值。例如。如果接收者是 :cx 我想要这个 '@cx_real' = '@ax_real'。
  • @ArupRakshit 是的,就是这样。但这取决于。可能是“@bx”、“@cx”等。

标签: ruby methods properties attributes variable-assignment


【解决方案1】:

尝试以下方法来消除错误:

 self.send(:populate,destination, source)

也请看Object#send

调用由符号标识的方法,将任何指定的参数传递给它。如果名称 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

【讨论】:

  • 但是为什么我必须在 self.send 中传递方法 'populate' 的名称?当我跳过它时,它会给我 ArgumentError。
  • @user2128702 看方法文档,我链接了。
  • 当我在我的代码中这样使用它时,我会进入堆栈溢出。也许有一个递归不断调用方法本身。这就是为什么我想知道我在填充方法本身内部执行 self.send(:populate, destination, source)。
  • 我不确定它是否适合我,因为方法调用的递归无穷无尽。我会更新我的问题
  • @user2128702 看到更新......并告诉我更多信息?
猜你喜欢
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多