【问题标题】:Transforming hash in ruby在 ruby​​ 中转换哈希
【发布时间】:2016-06-28 18:03:02
【问题描述】:

输入

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

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

【问题讨论】:

    标签: arrays ruby hash


    【解决方案1】:
    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"}]}}
    

    【讨论】:

      【解决方案2】:

      这会在原地替换

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

      【讨论】:

        【解决方案3】:

        真的和你的代码一样,但技术上有点 FP 风格...

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-12-22
          • 2010-12-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-08
          相关资源
          最近更新 更多