arr = [["a:1","b:0"],["c:2","b:0","d:5"]]
转换为
new_arr = [a=>{1,nil},b=>{0,0},c=>{nil,2},d=>{nil,5}]
求高手上面转换的写法。arr 中可能有若干元素 感谢!!!
。。。这肯定不是 ruby。。。
arr = [["a:1","b:0"],["c:2","b:0","d:5"]] hash = {} arr_size = arr.size arr.each_with_index do |a, i| a.each_with_object({}) do |str, h| str =~ /^(.*):(.*)$/ h[$1] = $2 end.each do |k, v| hash[k] ||= [nil] * arr_size hash[k][i] = v end end p hash
#2 楼 @piecehealth 看似不长的代码,其实很考功力。学习了,谢谢!
#3 楼 @chenge 写复杂了……
arr.each_with_index do |a, i| a.each do |str| str =~ /^(.*):(.*)$/ k, v = $1, $2 hash[k] ||= [nil] * arr_size hash[k][i] = v end end
就行
@piecehealth 好用!严重感谢!!!
很变态的数据格式。。。