我想从以下转换:
{"key1" => "value1","key2" => "value2"}
至
{key1: "value1", key2: "value2"}
目前,您必须这样做:
{"key1" => "value1", "key2" => "value2"}
.map{|k, v| [k.to_sym, v]}.to_h
# => {:key1=>"value1", :key2=>"value2"}
稍微更有效的是:
{"key1" => "value1", "key2" => "value2"}
.each_with_object({}){|(k, v), h| h[k.to_sym] = v}
# => {:key1=>"value1", :key2=>"value2"}
在不久的将来,Hash#transform_keys
可能会变得可用。