Iteration on a Ruby hash, unexpected behavior -


r = {} r[0] = [1, 2] r[2] = [1, 2, 4] r[4] = [1, 2, 5] r[6] = [1, 2]  count = 0 r.each |x|     count += x.length end   puts count #output 8 expected value 10 
  1. why behavior?
  2. how achieve expected behavior (getting sum of length)

each converts receiver hash array , iterates on it. each element of iteration consists of array of 2 elements: key , corresponding value. since have 4 key-value pairs, adds eight.

to acheive 10, can do:

r.each |x|   count += x.last.length end 

or

r.each |_, v|   count += v.length end 

or

r.values.flatten.length 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -