如何使用`map`获取数组

时间:2015-10-16 07:36:56

标签: arrays ruby hashmap

对于使用gem prawn的PDF表格,我想要这个:

[
  ["FIELDS", "RESULT"],
  ["会社名", "company 1"],
  ["担当者名", "contact person 1"],
  ["電話番号/FAX番号", "contact 1"],
  ["E-mailアドレス", "email 1"],
  ["会社名", "company 2"],
  ["担当者名", "contact person 2"],
  ["電話番号/FAX番号", "contact 2"],
  ["E-mailアドレス", "email 2"],
  ["会社名", "company 3"],
  ["担当者名", "contact person 3"],
  ["電話番号/FAX番号", "contact 3"],
  ["E-mailアドレス", "email 3"]
]

这是我的代码:

[["FIELDS", "RESULT"]] +
@customer.customer_details.map do |cd|
  ["会社名", cd.company_name.to_s] +
  ["担当者名", cd.name.to_s] +
  ["電話番号/FAX番号", cd.contact_number.to_s] +
  ["E-mailアドレス", cd.email.to_s]
end

并且,我得到了这个:

[
  ["FIELDS", "RESULT"],
  [
    "会社名", "company 1", "担当者名", "contact person 1", "電話番号/FAX番号", "contact 1", "E-mailアドレス", "email 1",
    "会社名", "company 2", "担当者名", "contact person 2", "電話番号/FAX番号", "contact 2", "E-mailアドレス", "email 2",
    "会社名", "company 3", "担当者名", "contact person 3", "電話番号/FAX番号", "contact 3", "E-mailアドレス", "email 3"
  ]
]

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

另一种方式,

result = [["FIELDS", "RESULT"]]
@customer.customer_details.each do |cd|
  result += [["会社名", cd.company_name.to_s],
  ["担当者名", cd.name.to_s],
  ["電話番号/FAX番号", cd.contact_number.to_s],
  ["E-mailアドレス", cd.email.to_s] ]
end

p result