开发者

In Ruby, some good ways to convert everything in array of hash values from float to int?

I have an array of hashes, and the values are all float numbers.

What are some good ways in Ruby to convert them all to int?

I have this way right now but wonder what other methods there are that are more elegant or clear:

analytics.map {|e| e.keys.each {|k| e[k] = e[k].to_i}; e}

Update: this is a run of the code:

> @analytics = [{:a => 1.1, :b => 123.456}, {'c' => 765.432}]
 => [{:a=>1.1, :b=>123.456}, {"c"=>765.432}] 

> @analytics.map {|e| e.keys.each {|k| 开发者_StackOverflow社区e[k] = e[k].to_i}; e} 
 => [{:a=>1, :b=>123}, {"c"=>765}] 

> @analytics
 => [{:a=>1, :b=>123}, {"c"=>765}]


analytics.map {|h| Hash[h.map {|k, v| [k, v.to_i] }] }

Looks kind of neat.

In general, whenever I find myself juggling several nested iterators, I try to refactor my object model such that I'm actually dealing with actual objects, not just a twisted maze of nested arrays and hashes. This seems to be right on the fence.

After all, Ruby is an object-oriented programming language, not a hash-oriented one.


In place:

a = [{:a=>1.1, :b=>2.1},{:a=>3.0, :b=>4.1}]
a.each {|h| h.each_pair {|k,v| h[k] = v.to_i}}
p a
# => [{:a=>1, :b=>2}, {:a=>3, :b=>4}]


This is a solution with FP style (no in-place modifications) that uses the handy Enumerate#mash from Facets:

analytics.map { |h| h.mash { |key, value| [key, value.to_i] } }

Enumerable#mash is a map+to_hash. See more info here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜