rubocop / rubocop/ruby-style-guide

Use `#fetch` for arrays?

Open
#781 0 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

New Rule
Dominant language
No language data
Stars
16.5k
Forks
3.3k
PR merge metrics
No merged PRs in 30d

Description

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?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Review the existing guide section that recommends #fetch for hashes and Ruby's Array#fetch behavior. Decide whether the guidance should extend to arrays, and record a clear recommendation with examples if maintainers agree.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.