我有这样的哈希
a={"Feb-13"=>"24176", "Aug-13"=>0, "May-13"=>0, "Jun-13"=>0, "Apr-13"=>0, "Oct-13"=>0, "Nov-13"=>0, "Jul-13"=>0, "Sep-13"=>0, "Jan-13"=>0, "Mar-13"=>0, "Dec-13"=>0}
但我需要像这样的哈希
a={"Feb"=>"24176", "Aug"=>0, "May"=>0, "Jun"=>0, "Apr"=>0, "Oct"=>0, "Nov"=>0 }
是否有其他方法,例如哈希更新。
答案 0 :(得分:3)
a={"Feb-13"=>"24176", "Aug-13"=>0, "May-13"=>0, "Jun-13"=>0, "Apr-13"=>0, "Oct-13"=>0, "Nov-13"=>0, "Jul-13"=>0, "Sep-13"=>0, "Jan-13"=>0, "Mar-13"=>0, "Dec-13"=>0}
Hash[a.map { |k, v| [k[0...3], v] }]
# => {"Feb"=>"24176", "Aug"=>0, "May"=>0, "Jun"=>0, "Apr"=>0, "Oct"=>0, "Nov"=>0, "Jul"=>0, "Sep"=>0, "Jan"=>0, "Mar"=>0, "Dec"=>0}
答案 1 :(得分:1)
这个怎么样?:
a.inject({}) { |initial, (k,v)| initial[k[0..2]] = v; initial }
#=> {"Feb"=>"24176",
"Aug"=>0,
"May"=>0,
"Jun"=>0,
"Apr"=>0,
"Oct"=>0,
"Nov"=>0,
"Jul"=>0,
"Sep"=>0,
"Jan"=>0,
"Mar"=>0,
"Dec"=>0}
或者:
Hash[a.map{ |x, y| [x[0..2], y] }]
#=> {"Feb"=>"24176",
"Aug"=>0,
"May"=>0,
"Jun"=>0,
"Apr"=>0,
"Oct"=>0,
"Nov"=>0,
"Jul"=>0,
"Sep"=>0,
"Jan"=>0,
"Mar"=>0,
"Dec"=>0}
答案 2 :(得分:1)
> Hash[a.map{|k,v| [k[/\w+/], v]}]
# => {"Feb"=>"24176", "Aug"=>0, "May"=>0, "Jun"=>0, "Apr"=>0, "Oct"=>0, "Nov"=>0, "Jul"=>0, "Sep"=>0, "Jan"=>0, "Mar"=>0, "Dec"=>0}