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