From 11279ac362ceed24c1fc95eb3232a6dd475873a5 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 14 Mar 2026 15:55:09 -0500 Subject: [PATCH] Add Load A Module And Execute A Statement as a Ruby TIL --- README.md | 3 ++- ruby/load-a-module-and-execute-a-statement.md | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 ruby/load-a-module-and-execute-a-statement.md diff --git a/README.md b/README.md index 6c626c7..4b70231 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1755 TILs and counting..._ +_1756 TILs and counting..._ See some of the other learning resources I work on: @@ -1451,6 +1451,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Limit Split](ruby/limit-split.md) - [List The Running Ruby Version](ruby/list-the-running-ruby-version.md) - [Listing Local Variables](ruby/listing-local-variables.md) +- [Load A Module And Execute A Statement](ruby/load-a-module-and-execute-a-statement.md) - [Make A Long String Of Text Readable](ruby/make-a-long-string-of-text-readable.md) - [Make An Executable Ruby Script](ruby/make-an-executable-ruby-script.md) - [Make Structs Easier To Use With Keyword Initialization](ruby/make-structs-easier-to-use-with-keyword-initialization.md) diff --git a/ruby/load-a-module-and-execute-a-statement.md b/ruby/load-a-module-and-execute-a-statement.md new file mode 100644 index 0000000..ac6aee4 --- /dev/null +++ b/ruby/load-a-module-and-execute-a-statement.md @@ -0,0 +1,25 @@ +# Load A Module And Execute A Statement + +Here is a nice one-liner pattern for use with the `ruby` executable. + +```bash +$ ruby -r file.rb -e 'MyClass.do_something' +``` + +The `-r` flag loads (requires, really) a Ruby file at the specified path. The +`-e` flag will execute the line of Ruby code that you give it, in that context. +In combination that means I can load some module into the execution environment +and then I can run some code that uses that module. + +A more practical example of that is how I demonstrated the behavior of a +`MarkdownHelpers` module in [Create A Module Of Utility +Functions](create-a-module-of-utility-functions.md). + +```bash +$ ruby -r ./markdown_helpers.rb -e 'puts MarkdownHelpers.link("Click here", "https://example.com")' +[Click here](https://example.com) +``` + +The `MarkdownHelpers` module that I've defined in `./markdown_helpers.rb` is +loaded into context and I can now access and execute that module to try out +parts of it. All in a single line in the terminal.