散列中每个键/值对的 ruby
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8407756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ruby for each key/value pair in a hash
提问by JP Silvashy
I have a bit of a problem with MongoDB in that it returns hashes with the keys in double quotes and integers as floats all the time, has this been a problem for anyone else?
我对 MongoDB 有一点问题,因为它始终返回带有双引号和整数作为浮点数的键的哈希值,这对其他人有没有问题?
for examples after a map reducing or grouping, say I have a bunch of hashes which look like this:
例如在地图减少或分组之后,假设我有一堆看起来像这样的哈希:
{"unknown"=>54.0, "pedestrians"=>572.0, "vehicles"=>1045.0}
But what I really want is:
但我真正想要的是:
{ unknown: 54, pedestrians: 572, vehicles: 1045 }
Any ideas on how I can easily convert it?
关于如何轻松转换它的任何想法?
回答by Russell
You could do:
你可以这样做:
original = {"unknown"=>54.0, "pedestrians"=>572.0, "vehicles"=>1045.0}
converted = Hash[ original.map { |key, value| [key.to_sym, value.to_i] } ]
Or if you're using Rails, you could make it a HashWithIndifferentAccessand just convert the values:
或者,如果您使用的是 Rails,则可以将其设为 aHashWithIndifferentAccess并仅转换值:
original = HashWithIndifferentAccess.new(original)
original.each { |key, value| original[key] = value.to_i }
回答by DigitalRoss
Trust Integral FP Values
信任积分 FP 值
In order to handle all possible key types correctly, if you are going to convert it I would suggest something like:
为了正确处理所有可能的密钥类型,如果您要转换它,我会建议如下:
h = {:a => 54.0, :b => 572.0, :c => 1045.0, :d => 'test', :e => 1.23 }
p(h.merge(h) do |k, v|
v = v.to_i if v.is_a?(Float) && v.to_i == v
v
end)
The above code will convert Float values in a hash that are actually integral to Integer.
上面的代码将转换散列中的浮点值,这些值实际上是整数的整数。
But you actually don't need to do this at all. While it's common to distrust the floating point formats, it turns out that they do represent integral values exactly.
但实际上您根本不需要这样做。虽然不信任浮点格式很常见,但事实证明它们确实准确地表示整数值。
You can trust that any value that was an integer in the database will compare exactly with integer constants (including 0) and that you will notsee any rounding artifacts.
您可以相信数据库中的任何整数值都将与整数常量(包括 0)进行精确比较,并且您不会看到任何舍入伪影。
You willnotice a difference, of course, if you divide a float by something other than a factor.
当然,如果您将浮点数除以因子以外的其他值,您会注意到差异。

