Programming Ruby 3.2 (5th Edition): B4.0 page 553, confusion about flatten

@noelrappin

page 553, in Converting Hashes, lines 2-3 :

… If you want a single-dimensional array,
you can use flatten, which is hash.to_a.flatten. By default, flatten does not flatten values that
happen to be arrays …

I have checked that :

irb(main):125:0> hash = {a: 1, b: 2, c: [3, [55,66]], d: 4}
=> {:a=>1, :b=>2, :c=>[3, [55, 66]], :d=>4}
irb(main):126:0> hash.to_a.flatten
=> [:a, 1, :b, 2, :c, 3, 55, 66, :d, 4]

Then I was confused to read that by default flatten does not flatten …

As Array#flatten behaves differently as Hash#flatten, I suggest to replace flatten by Hash#flatten :

By default, Hash#flatten does not flatten values that …

Okay, cleaned this up to:

If you want a single-dimensional array, you can use Hash#flatten(level = 1), which is equivalent to hash.to_a.flatten(level). By default, Hash#flatten does not recursively flatten values that happen to be arrays—you can do that with an optional argument that specifies how many levels of sub-array values are flattened.