100, "b" => 200, "c" => 300} b = a.map{|k,v| v = v + 10} returns an array, I...">

Error moving and changing Ruby Hash value does not work

a = {"a" => 100, "b" => 200, "c" => 300} b = a.map{|k,v| v = v + 10} 

returns an array, I need to change the hash values โ€‹โ€‹by calling by reference

I expect the next exit

 {"a" => 110, "b" => 210, "c" => 310} 

thanks

+4
source share
6 answers

Perhaps you can do something like this:

 a.keys.each do |key| a[key] += 10 end 
+6
source

Here is my non-mutating single-line layer: P

 Hash[original_hash.map { |k,v| [k, v+10] }] 

One must love ruby โ€‹โ€‹single-lineers :)

+8
source
 a.each_pair do |x,y| a[x] += 10 end 
+4
source

Reality check:

 require "benchmark" include Benchmark h0, h1, h2, h3, h4 = (0..4).map { Hash[(0..1000).map{ |i| [i,i] }] } bm do |x| x.report("0") { 1000.times { h0.each_key{ |k| h0[k] += 10 } } } x.report("1") { 1000.times { h1.keys.each{ |k| h1[k] += 10 } } } x.report("2") { 1000.times { Hash[h2.map { |k,v| [k, v+10] }] } } x.report("3") { 1000.times { h3.inject({}){ |h,(k,v)| h[k] = v + 10; h } } } x.report("4") { 1000.times { h4.inject({}){ |h,(k,v)| h.update( k => v + 10) } } } end user system total real 0 0.490000 0.000000 0.490000 ( 0.540795) 1 0.490000 0.010000 0.500000 ( 0.545050) 2 1.210000 0.010000 1.220000 ( 1.388739) 3 1.570000 0.010000 1.580000 ( 1.660317) 4 2.460000 0.010000 2.470000 ( 3.057287) 

Imperative programming wins.

+4
source

Dude, change the map to each and you're good to go :)

+1
source

I believe in every question Ruby inject : D

 b = a.inject({}){ |h,(k,v)| h[k] = v + 10; h } #=> {"a"=>110, "b"=>210, "c"=>310} 
+1
source

All Articles