2016-03-16 36 views
1

訪問許多領域目前我有這行代碼:快捷方式從同一個對象(紅寶石)

[@organisation.name, @organisation.address, @organisation.city, @organisation.postcode, @organisation.country, @organisation.phone_number].join(', ') 

看來不必要的冗長。

有沒有一種方法可以簡單說明@organisation一次,並從中獲得所需的各種字段?

回答

2

爲了清楚起見,我將其分隔爲單獨的行,但它可以是單行的。

fields = [:name, :address, :city, :postcode, :country, :phone_number] 
values = fields.map { |field| @organisation.send(field) } 
csv = values.join(', ') 

send方法是你以後的魔法。它將方法調用發送給對象並返回該方法調用的結果。

0

正如引用「發送」的答案所證明的那樣,您的問題不太清楚,但根據一種解釋,instance_variables將是您正在尋找的魔法。

1

如果您使用Ruby 2.3,你可以試試這個:

@organisation.attributes.fetch_values("name", "address", "city", "postcode", "country", "phone_number").join(', ') 
+0

什麼紅寶石<2.3,有什麼例如爲2.2? – Mirror318

+0

'fetch_values'方法在Ruby 2.3中實現。 對於Ruby <2.3,我想使用別人的解決方案將會很好。 – ShallmentMo