在ruby中转换哈希

时间:2016-06-28 18:03:02

标签: arrays ruby hash

输入

i = { :Narration=>"RI journal",
      :Status=>"DRAFT",
      :JournalLines=>{
        :JournalLine=>[
          { :credit=>{
              :LineAmount=>"10",
              :AccountCode=>"111",
              :Description=>"check cred"
            },
            :debit=>{
              :LineAmount=>"-10",
              :AccountCode=>"222"
            }
          },
          { :credit=>{
              :LineAmount=>"10",
              :AccountCode=>"333"
            },
            :debit=>{
              :LineAmount=>"-10",
              :AccountCode=>"444"
            }
          }
        ]
      }
    }

而不是'credit','debit',我只想简单地使用数组中的值。

预期产出:

{ :Narration=>"RI journal",
  :Status=>"DRAFT",
  :JournalLines=>
    { :JournalLine=>[
        {:LineAmount=>"10",  :AccountCode=>"111", :Description=>"check cred"},
        {:LineAmount=>"-10", :AccountCode=>"222"},
        {:LineAmount=>"10",  :AccountCode=>"333"},
        {:LineAmount=>"-10", :AccountCode=>"444"}
      ]
    }
}

这是我的代码,有效。

arr = []
i[:JournalLines][:JournalLine].each do |h|
  h.each do |k, v|
   arr << v
  end
end

有没有更好的方法来转换输入替换每个循环。

3 个答案:

答案 0 :(得分:0)

result = i.select {|k,_| [:Narration, :Status].include?(k)}
# => {:Narration=>"RI journal", :Status=>"DRAFT"} 

result[:JournalLines] = {:JournalLine => i[:JournalLines][:JournalLine].map{|hash| hash.flatten.select{|el| el.is_a?(Hash)}}.flatten}

result
# => {:Narration=>"RI journal", :Status=>"DRAFT", :JournalLines=>{:JournalLine=>[{:LineAmount=>"10", :AccountCode=>"111", :Description=>"check cred"}, {:LineAmount=>"-10", :AccountCode=>"222"}, {:LineAmount=>"10", :AccountCode=>"333"}, {:LineAmount=>"-10", :AccountCode=>"444"}]}}

答案 1 :(得分:0)

这就是替换

2.2.2 :071 > i[:JournalLines].update(JournalLine: i[:JournalLines][:JournalLine].map(&:values).flatten)
=> {:JournalLine=>[{:LineAmount=>"10", :AccountCode=>"111", :Description=>"check cred"}, {:LineAmount=>"-10", :AccountCode=>"222"}, {:LineAmount=>"10", :AccountCode=>"333"}, {:LineAmount=>"-10", :AccountCode=>"444"}]}
2.2.2 :072 > i
=> {:Narration=>"RI journal", :Status=>"DRAFT", :JournalLines=>{:JournalLine=>[{:LineAmount=>"10", :AccountCode=>"111", :Description=>"check cred"}, {:LineAmount=>"-10", :AccountCode=>"222"}, {:LineAmount=>"10", :AccountCode=>"333"}, {:LineAmount=>"-10", :AccountCode=>"444"}]}}

答案 2 :(得分:0)

与您的代码完全相同,但从技术上来说更像是FP风格......

arr = i[:JournalLines][:JournalLine].inject [] do |m, e|
  e.inject m do |m, (k, v)|
    m << v
  end
end