Skip to content

Commit 6029866

Browse files
author
Chad Shaffer
committed
Add general rules for accessing collection elements
* Prefer alternate method if it’s provided * Provide alternate methods in your accessor methods
1 parent cfe1d6a commit 6029866

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2975,6 +2975,42 @@ condition](#safe-assignment-in-condition).
29752975
Do not modify a collection while traversing it.
29762976
<sup>[[link](#no-modifying-collections)]</sup>
29772977

2978+
* <a name="acessing-elements-directly"></a>
2979+
When accessing elements of a collection, avoid direct access
2980+
via `[n]` by using an alternate form of the reader method if it is
2981+
supplied. This guards you from calling `[]` on `nil`.
2982+
<sup>[[link](#accessing-elements-directly)]</sup>
2983+
2984+
```Ruby
2985+
# bad
2986+
Regexp.last_match[1]
2987+
2988+
# good
2989+
Regexp.last_match(1)
2990+
```
2991+
2992+
* <a name="provide-alternate-accessor-to-collections"></a>
2993+
When providing an accessor for a collection, provide an alternate form
2994+
to save users from checking for `nil` before accessing an element in
2995+
the collection.
2996+
<sup>[[link](#provide-alternate-accessor-to_collections")]</sup>
2997+
2998+
```Ruby
2999+
# bad
3000+
def awesome_things
3001+
@awesome_things
3002+
end
3003+
3004+
# good
3005+
def awesome_things(index = nil)
3006+
if index && @awesome_things
3007+
@awesome_things[index]
3008+
else
3009+
@awesome_things
3010+
end
3011+
end
3012+
```
3013+
29783014
## Strings
29793015

29803016
* <a name="string-interpolation"></a>

0 commit comments

Comments
 (0)