-3

我想从以下转换:

{"key1" => "value1","key2" => "value2"}

{key1: "value1", key2: "value2"}
4

1 回答 1

2

目前,您必须这样做:

{"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可能会变得可用。

于 2017-10-04T06:26:06.100 回答