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

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -