BernardK
Programming Ruby 3.2 (5th Edition): B4.0 page 553, confusion about flatten
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 …
First Post!
noelrappin
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.
Popular Pragmatic Bookshelf topics
Other popular topics
Categories:
Sub Categories:
Popular Portals
- /elixir
- /rust
- /wasm
- /ruby
- /erlang
- /phoenix
- /keyboards
- /python
- /js
- /rails
- /security
- /go
- /swift
- /vim
- /clojure
- /java
- /emacs
- /haskell
- /svelte
- /onivim
- /typescript
- /kotlin
- /c-plus-plus
- /crystal
- /tailwind
- /react
- /gleam
- /ocaml
- /elm
- /flutter
- /vscode
- /ash
- /html
- /opensuse
- /zig
- /deepseek
- /centos
- /php
- /scala
- /react-native
- /lisp
- /textmate
- /sublime-text
- /nixos
- /debian
- /agda
- /django
- /deno
- /kubuntu
- /arch-linux
- /nodejs
- /revery
- /ubuntu
- /manjaro
- /spring
- /julia
- /lua
- /diversity
- /markdown
- /v









