我对MongoDB有一点问题,它返回带有双引号和整数的键的哈希,一直是浮点数,这对其他人来说是个问题吗?
例如,在地图缩小或分组之后,请说我有一堆看似如下的哈希:
{"unknown"=>54.0, "pedestrians"=>572.0, "vehicles"=>1045.0}
但我真正想要的是:
{ unknown: 54, pedestrians: 572, vehicles: 1045 }
关于如何轻松转换它的任何想法?
你可以这样做:
original = {"unknown"=>54.0, "pedestrians"=>572.0, "vehicles"=>1045.0} converted = Hash[ original.map { |key, value| [key.to_sym, value.to_i] } ]
或者,如果您正在使用Rails,您可以将其设为a HashWithIndifferentAccess
并只转换值:
original = HashWithIndifferentAccess.new(original) original.each { |key, value| original[key] = value.to_i }