2014-01-13 41 views
0

分配属性值有方法:我如何从方法在红宝石

def mov destination_register, source 
    if source == :ax then send("#{destination_register}=", @ax) end 
end 

其中destination_register是符号(:斧,:BXM:CX,:DX)。我也有属性:@ax,@ bx,@cx,@dx。如果source始终是以下符号之一:ax,:bx,:cx,:dx如何将destination_register属性的值与source的值分配?我尝试与发送,但我仍然不知道它是否会工作。有什么建议么 ?

+0

没错。该方法是包含在类中的模块的一部分,该类具有@ax – user2128702

+1

我很困惑。在你的问题中,你是说'source'是一个寄存器的名字,例如':ax'这意味着'mov'将会像'mov(:ax,:bx)'一样被使用,但是在这个评论中你应该说'mov'应该和一个值一起使用,比如'mov(:ax, 2)'? –

+0

我对你的回答感到困惑,但我认为你的问题是正确的(即'source'是寄存器的符号)。我将删除我之前的评论。 –

回答

1

这不是我清楚,你想做的事,但这样的事情可能工作:

def mov(destination_register, source) 
    send(:"#{destination_register}=", instance_variable_get(:"@{source}")) 
end 

但是,如果你有你的实例变量getter方法,这将是更好的使用该而不是直接获取实例变量:

def mov(destination_register, source) 
    send(:"#{destination_register}=", send(:"{source}")) 
end 

如果你想破坏封装反正,那么为什么不走整个九码:

def mov(destination_register, source) 
    instance_variable_set(:"#@{destination_register}", instance_variable_get(:"@{source}")) 
end 
+0

我想这会工作。我只是想问也:我怎么能从传递给它的两个参数的对象中调用mov方法?是否有这样的'发送'的方法名称和两个参数的版本,或者我只需要期待这个'* args'而不是两个位置参数? – user2128702

+0

'send'采用方法名称和无论您想传递多少参数。它只是将除第一个参数以外的所有参数传递给由第一个参数命名的方法。 –

1

下面应该工作:

def mov destination_register, source 
    instance_variable_set(:"#{destination_register}", instance_variable_get(:"@{source}") 
end