Rails在地图内连接数组而不进行转义

时间:2018-05-31 04:24:21

标签: ruby-on-rails

我有一个哈希数组,我将其映射为一个字符串 例如:

array_of_hashes = [{
  :me => 'happy',
  :you => 'notsohappy',
  :email => [
    {"Contact"=>"", "isVerified"=>"1"},
    {"Contact"=>"me@example.com", "isVerified"=>"1"},
    {"Contact"=>"you@example.com", "isVerified"=>"1"}
  ] 
},{another instance here...}]

现在我想把它转换为一个新的数组,它会给我:

["happy", "notsodhappy", "me@example.com", "you@example.com"]

我需要在“电子邮件”哈希数组中映射并拒绝空电子邮件地址。

到目前为止,我试过了:

array_of_hashes.map{|record| [
  record['me'],
  record['you'],
  record['email'].map { |email| email['Contact']}.reject { |c| c.empty? }.join('", "')
] }

但这会返回["happy", "notsohappy", "me@example.com\", \"you@example.com"]

即使我在.html_safe

之后添加.join,引号也是转义符号

简而言之,它坚持要将连接的数组保持为单个字符串。我需要将它拆分为单独的字符串......与数组中的字符串一样多。

我需要摆脱这些引号,因为我试图将数组导出为CSV,到目前为止,它并没有将电子邮件地址拆分为单独的列。

建议?

2 个答案:

答案 0 :(得分:3)

array_of_hashes.map do |h|
  [h[:me], h[:you]].push(
    h[:email].map {|e|e["Contact"]}.reject(&:empty?) 
  ).flatten
end

# => [["happy", "notsohappy", "me@example.com", "you@example.com"], ...]

答案 1 :(得分:0)

results = []
array_of_hashes.each do |hash|
  single_result = []
  single_result << hash[:me]
  single_result << hash[:you]
  hash[:email].each do |email|
   single_result << email["Contact"] if email["Contact"].present?
  end
  results << single_result
  return results
end

这将导致: -

2.3.1 :091 > results
 => [["happy", "notsohappy", "me@example.com", "you@example.com"], ["happy", "notsohappy", "me@example.com", "you@example.com"], ["happy", "notsohappy", "me@example.com", "you@example.com"]]