Skip to content

Commit 7de6c9a

Browse files
committed
Merge pull request #412 from cshaffer/regexp_last_match
Use Regexp.last_match(n) instead of Regexp.last_match[n]
2 parents 4240e24 + 6029866 commit 7de6c9a

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

README.md

Lines changed: 39 additions & 3 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>
@@ -3177,7 +3213,7 @@ condition](#safe-assignment-in-condition).
31773213

31783214
* <a name="no-perl-regexp-last-matchers"></a>
31793215
Don't use the cryptic Perl-legacy variables denoting last regexp group
3180-
matches (`$1`, `$2`, etc). Use `Regexp.last_match[n]` instead.
3216+
matches (`$1`, `$2`, etc). Use `Regexp.last_match(n)` instead.
31813217
<sup>[[link](#no-perl-regexp-last-matchers)]</sup>
31823218

31833219
```Ruby
@@ -3188,7 +3224,7 @@ condition](#safe-assignment-in-condition).
31883224
process $1
31893225

31903226
# good
3191-
process Regexp.last_match[1]
3227+
process Regexp.last_match(1)
31923228
```
31933229

31943230
* <a name="no-numbered-regexes"></a>
@@ -3200,7 +3236,7 @@ condition](#safe-assignment-in-condition).
32003236
# bad
32013237
/(regexp)/ =~ string
32023238
...
3203-
process Regexp.last_match[1]
3239+
process Regexp.last_match(1)
32043240

32053241
# good
32063242
/(?<meaningful_var>regexp)/ =~ string

0 commit comments

Comments
 (0)