i_love_ruby 发表于 2011-11-15 16:50

关于转换的问题

如何快速的将:

a = [{:one=>1},
{:two=>4},
{:one=>3},
{:three=>3}]

转换为:

a = [{:one=>4},
{:two=>4},
{:three=>3}]

coolesting 发表于 2011-11-16 17:22

h = {}
result = []

a.each do |t|
   t.each do |k,v|
      if h
         h += v
      else
         h = v
      end
   end
end

h.each do |k,v|
    result << {k=>v}
end没测试, 大概是这样

i_love_ruby 发表于 2011-11-16 17:39

#    data = []
    #    a.each do |h|
    #      if data.empty?
    #      data << h
    #      else
    #      eq = false
    #      data.each_with_index do |h_n,index|
    #          if h_n.to_a == h.to_a
    #            eq = true
    #            h_n] = h_n]+h]
    #          end
    #      end
    #      if !eq
    #          data<<h
    #      end
    #      end
    #    end
    #    data

i_love_ruby 发表于 2011-11-16 19:12

回复 2# coolesting


    你写的很简单很不错

coolesting 发表于 2011-11-17 11:04

回复 4# i_love_ruby


    过奖 :em03:

cinanine 发表于 2011-11-17 13:17

很不错
页: [1]
查看完整版本: 关于转换的问题