2016-06-28 10 views
0

入力代わりに「信用」、「借方」のルビー

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" 
      } 
      } 
     ] 
     } 
    } 

でハッシュの変換、私は単純に、配列内の値を求めています。

予想される出力:これは動作します私のコードは、

{ :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 

各ループを2つ置き換えて入力を変換する方法はありますか。

答えて

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"}]}} 
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"}]}} 
0

本当に同じ場所で置換を行いますが、技術的にビットがFP-風味もっと...

arr = i[:JournalLines][:JournalLine].inject [] do |m, e| 
    e.inject m do |m, (k, v)| 
    m << v 
    end 
end 
関連する問題