2014-01-13 38 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