ruby-style-guide
ruby-style-guide copied to clipboard
Use `#fetch` for arrays?
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?