将多个值从一个对象分配给另一个对象

时间:2022-06-01 20:54:22

I am trying to write a ruby function that iterates through an array of strings that are method names and uses the Object#send method to save values in a new instance object (not even sure if thats legit) that is a transformation of an already existing one. That's the best I can explain it. Here's the idea:

我正在尝试编写一个ruby函数,它遍历一个字符串数组,这些字符串是方法名称,并使用Object#send方法将值保存在一个新的实例对象中(甚至不确定这是否合法)是一个已经存在的转换一。这是我能解释的最好的。这是个主意:

@example = RelatedClass.new

def example_method
  instance_dependant_float = related_class.myvalue / other_related_class.myvalue

  ARRAY_OF_METHODS.each do |t|
    @example.send(t+'=', self.related_class.t * instance_dependant_float)
  end
end

When I try to run something like this where I call the index "t" on two separate ocassions (in my send and in the multiplier) it NoMethodError's on the second ocassion.

当我尝试运行这样的东西时,我在两个单独的ocassions(在我的发送和乘法器中)调用索引“t”,它在第二个ocassion上的NoMethodError。

1 个解决方案

#1


3  

You need to send to get the value also:

您还需要发送以获取值:

ARRAY_OF_METHODS.each do |name|
   @example.send( :"#{name}=", related_class.send(name) * some_float )
end

I always use and advocate string interpolation over String#+, and you don't need the self. to get the related_class.

我总是在String#+上使用和提倡字符串插值,而你不需要self。获取related_class。

#1


3  

You need to send to get the value also:

您还需要发送以获取值:

ARRAY_OF_METHODS.each do |name|
   @example.send( :"#{name}=", related_class.send(name) * some_float )
end

I always use and advocate string interpolation over String#+, and you don't need the self. to get the related_class.

我总是在String#+上使用和提倡字符串插值,而你不需要self。获取related_class。