2013-02-22 72 views
1

變量如果我有一個名爲數組:評估紅寶石

test_1 
test_2 

而且我有一個可以容納一個變量要麼12。即。 id,萬一ID具有價值1我怎麼能在這種情況下添加的東西到數組做:

test_1 << "value" 

更新:

TEST_1和test_2

test_#{id} << "value" #-> Where id is 1 

應該等執行是局部變量。

test_1 = [] 
test_2 = [] 

id = 1 

如何做到這一點:

爲test_id其中id是ID

回答

3

的價值隨着局部變量,你可以做這樣的:

test_1 = [] 
test_2 = [] 
eval("test_#{id}") << "value" 

你可以做到這一點輕微使用實例變量更好:

@test_1 = [] 
@test_2 = [] 
instance_variable_get("@test_#{id}") << "value" 

但更好的方法來處理這種情況是使用哈希與id的關鍵:

test = {1 => [], 2 => []} 
test[id] << "value" 
+1

假設索引是密集的,數組也可以工作而不是散列。我總是有點擔心在哈希中使用整數鍵... – 2013-02-22 10:05:48

+0

@HolgerJust在這種情況下,Array會使它變得複雜,因爲沒有索引爲'0'的條目。 – sawa 2013-02-22 10:07:26

+0

'test [id-1]'拯救:)或者你可以讓索引從零開始。 – 2013-02-22 10:09:36

3

對於這種情況,你應該使用Hash代替。

results = {} 
results['test_1'] = [] 
results['test_2'] = [] 

# If we sure that id is in [1,2]. Otherwise we need add check here, or change `results` definition to allow unexisting cases. 
results["test_#{id}"] << 'value' 
+1

雖然@sawa的答案有效,但它更清晰,因爲它涉及更少的魔法並更好地封裝數據。 – 2013-02-22 09:55:42