2011-11-23 66 views
0

我在Ruby中有這樣的代碼有可能把它寫得更短嗎?Ruby數組優化代碼

first_name = person[0] 
    last_name = person[1] 
    person_id = person[2] 
    email = person[3] 
    title = person[4] 
    phone = person[5] 
    mobile = person[6] 
    department = person[7] 
    address = person[8] 
    city = person[9] 
    zip_code =person[10] 
    state =person[11] 
    country = person[12] 
    manager_id = person[13] 
+4

這看起來像'person'應該開始用哈希。 –

+6

或者,你知道,一個'人'。 –

+0

這個問題似乎是脫離主題,因爲它是關於http://codereview.stackexchange.com – MikDiet

回答

3
ruby-1.9.2-p290 :001 > a = [1,2,3,4] 
=> [1, 2, 3, 4] 
ruby-1.9.2-p290 :002 > v1, v2, v3, v4 = a 
=> [1, 2, 3, 4] 
ruby-1.9.2-p290 :008 > puts v1, v2, v3, v4 
1 
2 
3 
4 
5
first_name, 
    last_name, 
    person_id, 
    email, 
    title, 
    phone, 
    mobile, 
    department, 
    address, 
    city, 
    zip_code, 
    state, 
    country, 
    manager_id = person 
2

當然,你可以寫一段代碼在更短的方式,如@fuzzyalej和@約爾格已經證明。但是,你應該嗎?它非常脆弱,如果在某個時候您決定在person陣列中的新索引中添加新數據,現有代碼將會中斷。

如果可能,您應該將所有人員信息包裝在課程或散列中。

+1

是啊,或哈希! :) – fuzzyalej

+0

謝謝@fuzzyalej,我編輯了我的答案,包括您的建議 –

2

嘗試

first_name, last_name, person_id = person