Ruby for each key / value pair in the hash

I have a bit of a problem with MongoDB in that it returns hashes with keys in double quotes and integers as floating all the time, is this a problem for someone else?

for examples, after cutting or grouping a map, let's say I have a bunch of hashes that look like this:

{"unknown"=>54.0, "pedestrians"=>572.0, "vehicles"=>1045.0} 

But I really want:

 { unknown: 54, pedestrians: 572, vehicles: 1045 } 

Any ideas on how I can easily convert it?

+7
source share
2 answers

You can 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 use Rails, you can do this with HashWithIndifferentAccess and simply convert the values:

 original = HashWithIndifferentAccess.new(original) original.each { |key, value| original[key] = value.to_i } 
+16
source

FP Integral Target Values

To handle all possible types of keys 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 converts the Float values ​​to a hash that are actually integral to Integer.

But you don’t have to do this at all. Although there is a mistrust of floating point formats, it turns out that they really are integral values.

You can trust that any value that was an integer in the database will be accurately compared to integer constants (including 0) and that you won't see rounding artifacts.

You will notice the difference, of course, if you divide the float into something other than the factor.

+2
source

All Articles