ruby-style-guide icon indicating copy to clipboard operation
ruby-style-guide copied to clipboard

Use `#fetch` for arrays?

Open andyw8 opened this issue 5 years ago • 0 comments

The guide advises using fetch for hashes. I discovered recently that Array also supports fetch, so that attempting to retrieve a non-existing element raises an IndexError rather than returning nil:

> x = ['a','b']
 => ["a", "b"]
> x[4]
 => nil
> x.fetch(4)
IndexError: index 4 outside of array bounds: -2...2

There may be situations where the nil behaviour is convenient, but I suspect that the majority of the time, it would be preferable to raise an error to avoid nils being unintentionally passed around.

Any thoughts?

andyw8 avatar Nov 17 '19 21:11 andyw8