Ruby: Use `Array(thing)` instead of `thing || []`

| ruby til

I learned something recently. Our code used to be peppered with this:

result = something.else || []

Or variations on the theme:

a_string = (something.else || []).join(',')

Turns out you can just

result = Array(something.else)
a_string = Array(something.else).join(',')

Minor convenience, but lovely nonetheless.

Hero image by F. Muhammad from Pixabay

Built with ❤ by Paweł J. Wal in 2023. Hugo helped.

Blog contents, except where otherwise noted, are CC BY-SA 4.0. Code of this blog is MIT.

Toggle dark/light mode