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
- why behavior?
- 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
Post a Comment