diff --git a/README.md b/README.md index 5a38535..ea8de20 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1089 TILs and counting..._ +_1090 TILs and counting..._ --- @@ -943,6 +943,7 @@ _1089 TILs and counting..._ - [Apply Multiple Substitutions To The Input](sed/apply-multiple-substitutions-to-the-input.md) - [Extract Value From Command Output With Sed](sed/extract-value-from-command-output-with-sed.md) +- [Grab All The Method Names Defined In A Ruby File](sed/grab-all-the-method-names-defined-in-a-ruby-file.md) - [Output Only Lines Involved In A Substitution](sed/output-only-lines-involved-in-a-substitution.md) - [Use An Alternative Delimiter In A Substitution](sed/use-an-alternative-delimiter-in-a-substitution.md) diff --git a/sed/grab-all-the-method-names-defined-in-a-ruby-file.md b/sed/grab-all-the-method-names-defined-in-a-ruby-file.md new file mode 100644 index 0000000..0b7d0fd --- /dev/null +++ b/sed/grab-all-the-method-names-defined-in-a-ruby-file.md @@ -0,0 +1,27 @@ +# Grab All The Method Names Defined In A Ruby File + +I wanted a listing of all the methods defined in a Ruby file. Metaprogramming +aside, I figured I could write a one-line `sed` script to effectively do this. + +```bash +$ sed -n 's/[[:space:]]*def \([[:alnum:]_?!]*\).*/\1/p' file.rb +``` + +Let's break this down. + +- `[[:space:]]*` accounts for any level of indentation. +- `def ` matches againts the start of a method definition. +- `\(...\)` is a capture that can be referenced in the replace side of the + script. +- `[[:alnum:]_?!]*` represents the characters that can make up a Ruby method + name, this is equivalent to writing `[a-zA-Z0-9_?!]*`. +- `.*` is the final part of the regex match which ensures the rest of the line + is loaded into the pattern space so that the replacement will only be the + method name. +- `\1` replaces everything in the first part of the script with the capture + which is just the method name. +- combining the `-n` and `p` flags ensures that only lines with substitutions + are printed. + +This probably isn't perfect, but it is good enough to reference from time to +time in my shell history.